20

I got error: Info doesn't implement Display (required by {}):11 while running this code:

struct Info<'a> {
    name: &'a str,
    age: u8,
}

fn main() {
    let john = Info {
        name: "John",
        age: 32,
    };
        println!("{}", john);
}

I have no idea what im doing wrong. Can anyone explain me?

masonrye
  • 301
  • 2
  • 3
  • 1
    Does this answer your question? [How to print structs and arrays?](https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays) – justinas Jun 24 '21 at 21:37

1 Answers1

21

In order for a struct to be formatable via "{}" format specifier it needs to implement the std::fmt::Display trait.
Therefore, to make your code compile, you need to impl Display for Info:

impl std::fmt::Display for Info<'_> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "My name is {} and I'm {} years old.", self.name, self.age)
    }
}

Note that Display trait is idiomatically used for user-facing representations.

Alternatively, you could use "{:?}" format specifier and #[derive(Debug)] annotation on your type to use formatter provided by std::fmt::Debug trait:

#[derive(Debug)]
struct Info<'a> {
    name: &'a str,
    age: u8,
}

fn main() {
    let john = Info {
        name: "John",
        age: 32,
    };
    println!("{:?}", john);
}
Ivan C
  • 1,772
  • 1
  • 8
  • 13
  • 2
    thank you @Ivan C, this helped a lot coming from mostly python and js, where you just take it for granted console or print and get something logged out – Gavin Apr 08 '22 at 15:35