Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, what's the difference between "{}" and "{:?}" inside a println!? [duplicate]

Tags:

rust

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?

like image 816
rusty_programmer Avatar asked Dec 15 '16 03:12

rusty_programmer


1 Answers

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

like image 60
Simon Whitehead Avatar answered Oct 13 '22 16:10

Simon Whitehead