How to print a Vec?
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 {:?}
Does anyone implement this trait for
Vec<T>
?
No.
And surprisingly, this is a demonstrably correct answer; which is rare since proving the absence of things is usually hard or impossible. So how can we be so certain?
Rust has very strict coherence rules, the impl Trait for Struct
can only be done:
- either in the same crate as
Trait
- or in the same crate as
Struct
and nowhere else; let's try it:
impl<T> std::fmt::Display for Vec<T> {
fn fmt(&self, _: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
Ok(())
}
}
yields:
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> src/main.rs:1:1
|
1 | impl<T> std::fmt::Display for Vec<T> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
|
= note: only traits defined in the current crate can be implemented for a type parameter
Furthermore, to use a trait, it needs to be in scope (and therefore, you need to be linked to its crate), which means that:
- you are linked both with the crate of
Display
and the crate ofVec
- neither implement
Display
forVec
and therefore leads us to conclude that no one implements Display
for Vec
.
As a work around, as indicated by Manishearth, you can use the Debug
trait, which is invokable via "{:?}"
as a format specifier.