8

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>`
1
  • It looks lke you changed your question to a different question, and now the answers don't fit the question anymore. Please use the "Ask Question" button to ask a new question, rather than editing an old question. I'm rolling back your changes. Commented Jul 2, 2020 at 8:35

2 Answers 2

6

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

How can I return a result instead of Vec<String> Ex: Result< Vec<String>, InvalidError> > { .... .... }
@rusty Just change the return type of the function, and wrap the return value in Ok().
2

You're getting an error because split_whitespace returns a &str. I see two options:

  • return a Vec<&str>
  • convert the result of split_whitespace by using map(|s| s.to_string())

2 Comments

How can I return a result instead of Vec<String> Ex: Result< Vec<String>, InvalidError> > { .... .... }
You change the return type, and wrap the result in a Ok() see here. Maybe change your question to include this if it's very important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.