Display Trait for Vector

Hi,

I want to print a Vec of structs in a custom way.

Is there another solution than packing the Vector into a tuple struct? Prefixing every access with .0 and converting everything to the new type seems to much overhead to print the vector. (Rust Playground)

You can use itertools' .format() or .format_with() iterator methods. format() is simple but format_with() is versatile enough you should be able to do exactly the thing in your code snippet.

1 Like

@PSeitz

Why you should change all your program? Wrap only for printing:

let vec = vec![Foo{val:5}, Foo{val:6}];
println!("Results: {}", PrintVec(&vec));
2 Likes

Thanks for the suggestions.
When I have to explicit call a method or convert the structure, would there be an advantage to a simple vec_to_pretty_string() method?

Because with Display trait you can write to file without heap allocation to for String,
write to array/Vec for network/gui communication also without allocations.