FAQ - Help and questions

How do I fix "doesn't implement std::fmt::Display" when printing a struct?

#errors#traits#formattingpublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

The {} placeholder needs the Display trait, which you write yourself because the compiler cannot know how your type should look to a user. Implement fmt::Display with write!, or print with {:?} after adding #[derive(Debug)] for a developer-oriented view.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

println!("{}", value) asks for the user-facing text of the value, through the Display trait. Numbers and strings have it. Your own structs do not, because there is no single right way to print them. Rust offers two formatting traits, and you choose per use:

  • {} uses Display: written by hand, meant for end users.
  • {:?} uses Debug: can be generated with #[derive(Debug)], meant for developers. {:#?} prints it over several lines.
src/main.rsrust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{}", p);
}
text
error[E0277]: `Point` doesn't implement `std::fmt::Display`
 --> src/main.rs:8:20
  |
8 |     println!("{}", p);
  |               --   ^ `Point` cannot be formatted with the default formatter
  |               |
  |               required by this formatting parameter
  |
help: the trait `std::fmt::Display` is not implemented for `Point`
 --> src/main.rs:1:1
  |
1 | struct Point {
  | ^^^^^^^^^^^^
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.

The answers below are the two fixes.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: implement Display#

    Write the text a user should see. write! works like println! but into the formatter.

    src/main.rsrust
    use std::fmt;
    
    struct Point {
        x: i32,
        y: i32,
    }
    
    impl fmt::Display for Point {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "({}, {})", self.x, self.y)
        }
    }
    
    fn main() {
        let p = Point { x: 1, y: 2 };
        println!("{}", p);
    }
    text
    (1, 2)

    Best when: the value is shown to users, put into messages, or turned into a String with .to_string() (which Display gives you for free).

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: derive Debug and use {:?}#

      Add #[derive(Debug)] above the struct and print with {:?}. The output looks like Point { x: 1, y: 2 }, field names included.

      Best when: you are debugging, logging, or writing tests (assert_eq! needs Debug to show the two sides when they differ).

      Common mistakes#

      • Deriving Debug and showing its output to users. The format can change with the field layout, and it exposes internal names.
      • Implementing Display for a type you do not own (Vec<i32>). The "orphan rule" forbids it; wrap the value in your own struct, or join the items yourself.
        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail