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()
}
I had to make the following adjustments:
Vec<String>
, because you construct String
objects anyway, so you'll have to own them in the vectorString
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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.