Display Trait for Vector


#1

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. (https://is.gd/jnFYvw)


#2

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.


#3

@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));

#4

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?


#5

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.