Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Print struct - implement Display

  • impl
  • Display
  • Formatter
use std::fmt;

struct Animal {
    name: String,
    size: String,
    weight: i32,
}

impl std::fmt::Display for Animal {
    fn fmt(&self, format: &mut fmt::Formatter) -> fmt::Result {
        write!(
            format,
            "name: {}, size: {}, weight: {}",
            self.name, self.size, self.weight
        )
    }
}

fn main() {
    let eli = Animal {
        name: String::from("elephant"),
        size: String::from("huge"),
        weight: 100,
    };
    println!("{}", eli.name);
    println!("{}", eli.size);
    println!("{}", eli.weight);

    println!("{}", eli);
}
elephant
huge
100
name: elephant, size: huge, weight: 100