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);
}