我应该使用 last_mut() 和 Option 在我的 Rust 代码中更改什么?

问题描述

我的 Rust 代码解决问题时遇到了问题,无法将给定的字符串拆分为一对椅子。起初我使用了 last(),但在更改最后一个元素时出现错误。我将 last() 替换为 last_mut()

fn solution(s: &str) -> Vec<String> {
    let mut result: Vec<String> = vec!["".to_string()];
    for member in s.chars() {
        if result.last_mut().len() < 2 {
            result.last_mut().push_str(member.to_string());
        } else {
            result.push("".to_string());
            result.last_mut().push_str(member.to_string());
        }
    }
    if result.last_mut().len() < 2 {
        result.last_mut().push_str("_");
    }
    result
}

此代码必须像示例中那样按对返回椅子

solution("abcdef") // should return ["ab","cd","ef"]
solution("abcdefg") // should return ["ab","ef","g_"]

但它返回错误

error[E0599]: no method named `len` found for enum `Option<&mut String>` in the current scope
 --> src/lib.rs:6:30
  |
6 |         if result.last_mut().len() < 2 {
  |                              ^^^ method not found in `Option<&mut String>`

error[E0599]: no method named `push_str` found for enum `Option<&mut String>` in the current scope
 --> src/lib.rs:7:31
  |
7 |             result.last_mut().push_str(member.to_string());
  |                               ^^^^^^^^ method not found in `Option<&mut String>`

error[E0599]: no method named `push_str` found for enum `Option<&mut String>` in the current scope
  --> src/lib.rs:10:31
   |
10 |             result.last_mut().push_str(member.to_string());
   |                               ^^^^^^^^ method not found in `Option<&mut String>`

error[E0599]: no method named `len` found for enum `Option<&mut String>` in the current scope
  --> src/lib.rs:13:26
   |
13 |     if result.last_mut().len() < 2 {
   |                          ^^^ method not found in `Option<&mut String>`

error[E0599]: no method named `push_str` found for enum `Option<&mut String>` in the current scope
  --> src/lib.rs:14:27
   |
14 |         result.last_mut().push_str("_");
   |                           ^^^^^^^^ method not found in `Option<&mut String>`

我应该在代码中替换什么以使其与 Option 一起使用?这对我来说是新的建筑。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)