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

Derive Debug for struct

  • derive

  • Debug

  • We don't need to implement the fmt method of the Debug trait ourselves. We can derive it:

#[derive(Debug)]
struct Animal {
    name: String,
    size: String,
    weight: i32,
}

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);
    dbg!(eli);
}
elephant
huge
100
Animal { name: "elephant", size: "huge", weight: 100 }
[src/main.rs:16] eli = Animal {
    name: "elephant",
    size: "huge",
    weight: 100,
}