This code works:
let x = Some(2);
println!("{:?}", x);
But this does not:
let x = Some(2);
println!("{}", x);
5 | println!("{}", x); | ^ trait `std::option::Option: std::fmt::Display` not satisfied | = note: `std::option::Option` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string = note: required by `std::fmt::Display::fmt`
Why? What's :?
in that context?
{:?}
, or, specifically, ?
, is the placeholder used by the Debug
trait. If the type does not implement Debug
, then using {:?}
in a format string breaks.
For example:
struct MyType {
the_field: u32
}
fn main() {
let instance = MyType { the_field: 5000 };
println!("{:?}", instance);
}
..fails with:
error[E0277]: the trait bound `MyType: std::fmt::Debug` is not satisfied
Implementing Debug
though, fixes that:
#[derive(Debug)]
struct MyType {
the_field: u32
}
fn main() {
let instance = MyType { the_field: 5000 };
println!("{:?}", instance);
}
Which outputs: MyType { the_field: 5000 }
.
You can see a list of these placeholder/operators in the documentation.
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