format!
already returns a String
, so there's no need for String::from(format!(...))
, and it's also an error because it expects a &str
, not a String
returned by format!
.
You'll also get an error in the lambda:
string = string + String::from(format!(...))
...even if you remove String::from
, because it's not possible to add two String
s like that, but it is possible to add a String
and a &str
, so I think you should borrow like this:
string = string + &format!(...)
The same goes for this line:
string = string + &(format!("And all for the want of a {}.", list[0])).to_string();
Moreover, your usage of map
won't actually execute the lambda for each element of the range. It'll just create a Map
iterator, over which you'll have to iterate with a loop to actually make it execute the lambda, so you could as well iterate over the range itself and modify your string in the loop.
I'm also not terribly sure about why you're returning string.to_string()
when you could've returned string
itself.
I also think you have an off-by-one error in your range, so after fixing that, I ended up with this:
fn do_it(list: Vec<&str>) -> String {
let mut string = format!("For want of a {} the {} was lost.\n", list[0], list[1]);
// BTW, you don't need this `if` statement because empty ranges, like `2..2`, are perfectly fine
if list.len() > 2 {
// These ranges do not include `list.len()`, so your program won't panic, because this index doesn't exist
for x in 2 .. list.len() {
string += &format!("For want of a {} the {} was lost.\n", list[x], list[x-1])
}
}
string + &format!("And all for the want of a {}.", list[0]) // Return the result of concatenation
}
fn main() {
let list = vec!["something", "test", "StackOverflow"];
let result = do_it(list);
println!("The result is: {}", result)
}
Output (it works, but your post doesn't say what it should output, so I can't say if it's the correct result):
The result is: For want of a something the test was lost.
For want of a StackOverflow the test was lost.
And all for the want of a something.