Vec<&str>` cannot be built from an iterator over elements of type ()

Viewed 63

I am new to rust and cannot figure out why I can not collect after map:

fn spin_words(words: &str) -> String {
    let split = words.split(" ");
    let mut spinned: Vec<&str> = split
        .into_iter()
        .map(|x: &str| {
            if (x.len() >= 5) {
                x.to_string()
                    .chars()
                    .rev()
                    .collect::<String>()
                    .push_str(" ")
            } else {
                x.to_string().push_str(" ")
            }
        })
        .collect();

    //just returning empty string for the compiler
    "".to_string()
}
1 Answers

I had to make the following adjustments:

  1. Collect into Vec<String>, because you construct String objects anyway, so you'll have to own them in the vector
  2. Instead of instantiating a String and expanding it with data using .push_str(), you can instead chain the .chars() iterator with some other iterator and then collect into a String. Note that .push_str() is also a valid way of doing it, however it would be more verbose, as String::push_str() doesn't return anything, so you'd have to create some intermediate variables to hold your string.
fn spin_words(words: &str) -> String {
    let split = words.split(" ");
    let mut spinned: Vec<String> = split
        .into_iter()
        .map(|x: &str| {
            if (x.len() >= 5) {
                x.chars()
                 .rev()
                 .chain(" ".chars())
                 .collect::<String>()
            } else {
                x.chars().chain(" ".chars()).collect::<String>()
            }
        })
        .collect();

    //just returning empty string for the compiler
    "".to_string()
}
Related