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

rus*_*sty 8 string vector rust

如何通过分割中间有空格的字符串来返回字符串向量

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

上面的代码返回这个错误

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>`
Run Code Online (Sandbox Code Playgroud)

Mic*_*son 6

如果您想返回,您需要将您获得的Vec<String>转换为. 转换迭代器类型的一种方法是使用. 要转换为的函数是. 把这些放在一起给你Iterator<Item=&str>split_whitespaceIterator<Item=String>Iterator::map&strStringstr::to_string

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