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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With