I tried the following code:
fn main() { let v2 = vec![1; 10]; println!("{}", v2); }
But the compiler complains:
error[E0277]: `std::vec::Vec<{integer}>` doesn't implement `std::fmt::Display` --> src/main.rs:3:20 | 3 | println!("{}", v2); | ^^ `std::vec::Vec<{integer}>` cannot be formatted with the default formatter | = help: the trait `std::fmt::Display` is not implemented for `std::vec::Vec<{integer}>` = 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<T>
?
But using C++ 17 experimental::make_ostream_joiner, it is possible to print all elements of a vector without specifying the type of elements in the vector while calling copy().
let v2 = vec! [1; 10]; println!
In the for loop, size of vector is calculated for the maximum number of iterations of loop and using at(), the elements are printed. for(int i=0; i < a. size(); i++) std::cout << a.at(i) << ' '; In the main() function, the elements of vector are passed to print them.
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:
Trait
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:
Display
and the crate of Vec
Display
for Vec
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With