snippetrustCritical
How to print a Vec?
Viewed 0 times
printhowvec
Problem
I tried the following code:
But the compiler complains:
Does anyone implement this trait for
fn main() {
let v2 = vec![1; 10];
println!("{}", v2);
}But the compiler complains:
error[E0277]: std::vec::Vec doesn't implement std::fmt::Display
--> src/main.rs:3:20
|
3 | println!("{}", v2);
| ^^ std::vec::Vec cannot be formatted with the default formatter
|
= help: the trait std::fmt::Display is not implemented for std::vec::Vec
= note: in format strings you may be able to use {:?} (or {:#?} for pretty-print) instead
= note: required by std::fmt::Display::fmt
Does anyone implement this trait for
Vec?Solution
let v2 = vec![1; 10];
println!("{:?}", v2);{} is for strings and other values which can be displayed directly to the user. There's no single way to show a vector to a user.The
{:?} formatter can be used to debug it, and it will look like:[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Display is the trait that provides the method behind {}, and Debug is for {:?}Code Snippets
let v2 = vec![1; 10];
println!("{:?}", v2);Context
Stack Overflow Q#30320083, score: 235
Revisions (0)
No revisions yet.