Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
833 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 {:?}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...