How to return a vector of strings in rust

rust, string, vector

Solution

If you want to return `Vec<String>` you need to convert the `Iterator<Item=&str>` that you get from `split_whitespace` into an `Iterator<Item=String>`. One way to convert iterator types is using `Iterator::map`. The function to convert `&str` to `String` is `str::to_string`. Putting this together gives you

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

Problem

How can I return a vector of strings by splitting a string that has spaces in between ``` fn line_to_words(line: &str) -> Vec<String> { line.split_whitespace().collect() } fn main() { println!( "{:?}", line_to_words( "string with spaces in between" ) ); } ``` The above code returns this error ``` 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>` ```

Original source