11

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?

1 Answers1

15

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

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138