如何在Rust中返回一个字符串向量

7

如何通过分割包含空格的字符串返回一个字符串向量?

fn line_to_words(line: &str) -> Vec<String> {     
    line.split_whitespace().collect()
}
    
fn main() {
    println!( "{:?}", line_to_words( "string with spaces in between" ) );
}

以上代码返回以下错误

line.split_whitespace().collect()
  |                           ^^^^^^^ value of type `std::vec::Vec<std::string::String>` cannot be built from `std::iter::Iterator<Item=&str>`
  |
  = help: the trait `std::iter::FromIterator<&str>` is not implemented for `std::vec::Vec<std::string::String>`

看起来你把问题改成了另一个问题,现在答案不再适用于这个问题。请使用“提问”按钮提出一个新问题,而不是编辑旧问题。我正在撤销你的更改。 - Sven Marnach
2个回答

6

如果你想返回Vec<String>,你需要将从split_whitespace获取到的Iterator<Item=&str>转换为Iterator<Item=String>。转换迭代器类型的一种方法是使用Iterator::map

&str转换为String的函数是str::to_string。将它们结合起来可以得到:

fn line_to_words(line: &str) -> Vec<String> {
    line.split_whitespace().map(str::to_string).collect()
}

如何返回结果而不是Vec<String>?例如:Result<Vec<String>, InvalidError> > { .... .... } - rusty
1
@rusty 只需更改函数的返回类型,并将返回值包装在Ok()中即可。 - Sven Marnach

2

你遇到错误是因为 split_whitespace 返回了一个 &str。我看到有两个选择:

  • 返回一个 Vec<&str>
  • 通过使用 map(|s| s.to_string()) 转换 split_whitespace 的结果

如何返回结果而不是Vec<String>呢? 例如:Result< Vec<String>, InvalidError> > { .... .... } - rusty
1
你可以更改返回类型,并将结果包装在 Ok()请参见此处。如果这非常重要,也许你需要修改你的问题来包含这一点。 - ShadowMitia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接