How to print a Vec?

后端 未结 5 1834
Happy的楠姐
Happy的楠姐 2020-12-03 00:21

I tried the following code:

fn main() {
    let v2 = vec![1; 10];
    println!(\"{}\", v2);
}

But the compiler complains:



        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 00:51

    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.)

提交回复
热议问题