Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: `Info` doesn't implement `Display` (required by {})

Tags:

rust

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?

like image 755
masonrye Avatar asked Sep 13 '25 21:09

masonrye


1 Answers

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);
}
like image 71
Ivan C Avatar answered Sep 15 '25 15:09

Ivan C