I tried the following code:
fn main() {
let v2 = vec![1; 10];
println!(\"{}\", v2);
}
But the compiler complains:
Here is a one-liner which should also work for you:
println!("[{}]", v2.iter().fold(String::new(), |acc, &num| acc + &num.to_string() + ", "));
Here is a runnable example.
In my own case, I was receiving a Vec<&str>
from a function call. I did not want to change the function signature to a custom type (for which I could implement the Display
trait).
For my one-of case, I was able to turn the display of my Vec
into a one-liner which I used with println!()
directly as follows:
println!("{}", myStrVec.iter().fold(String::new(), |acc, &arg| acc + arg));
(The lambda can be adapted for use with different data types, or for more concise Display
trait implementations.)