I tried the following code:
let v2 = vec![1; 10];
println!("{}", v2);
But the compiler complains that:
error[E0277]: the trait bound `std::vec::Vec<{integer}>: std::fmt::Display` is not satisfied
--> src/main.rs:3:20
|
3 | println!("{}", v2);
| ^^ trait `std::vec::Vec<{integer}>: std::fmt::Display` not satisfied
|
= note: `std::vec::Vec<{integer}>` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
= note: required by `std::fmt::Display::fmt`
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:Trait
Struct
and nowhere else; let's try it:
yields:
Furthermore, to use a
trait
, it needs to be in scope (and therefore, you need to be linked to its crate), which means that:Display
and the crate ofVec
Display
forVec
and therefore leads us to conclude that no one implements
Display
forVec
.As a work around, as indicated by Manishearth, you can use the
Debug
trait, which is invokable via"{:?}"
as a format specifier.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 theDisplay
trait).For my one-of case, I was able to turn the display of my
Vec
into a one-liner which I used withprintln!()
directly as follows:(The lambda can be adapted for use with different data types, or for more concise
Display
trait implementations.){}
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, however{:?}
can be used to debug it, and it will look like:Display
is the trait that provides the method behind{}
, andDebug
is for{:?}
If you know the type of the elements that the vector contains, you could make a struct that takes vector as an argument and implement
Display
for that struct.