Traits and Generics
Derive Debug
Printing a Struct
#[derive(Debug)] generates a debug formatter so a struct can be printed with {:?}.
Program
Play the program to print a point using its derived Debug output.
derive_debug.rs
Replay: real traced execution (multi-file project)
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let x = 1;
let y = 2;
let p = Point { x, y };
println!("{p:?}");
}
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let x = -3;
let y = 2;
let p = Point { x, y };
println!("{p:?}");
}
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let x = 5;
let y = 2;
let p = Point { x, y };
println!("{p:?}");
}
x ← 1, y ← 2, p ← Point { x: 1, y: 2 }
7fn main() {8 let → 1x = 1; //@x=1, 5, -39 let → 2y = 2;10 let → Point { x: 1, y: 2 }p = Point { 1x, 2y };11 println!("{p:?}");12}outputPoint { x: 1, y: 2 }
x ← -3, y ← 2, p ← Point { x: -3, y: 2 }
7fn main() {8 let → -3x = -3;9 let → 2y = 2;10 let → Point { x: -3, y: 2 }p = Point { -3x, 2y };11 println!("{p:?}");12}outputPoint { x: -3, y: 2 }
x ← 5, y ← 2, p ← Point { x: 5, y: 2 }
7fn main() {8 let → 5x = 5;9 let → 2y = 2;10 let → Point { x: 5, y: 2 }p = Point { 5x, 2y };11 println!("{p:?}");12}outputPoint { x: 5, y: 2 }
Follow the Debug Print
xstarts as1.ystarts as2.Point { x, y }buildsPoint { x: 1, y: 2 }.#[derive(Debug)]letsprintln!("{p:?}")print the struct fields.- The program prints
Point { x: 1, y: 2 }. | x | y | debug output | | --- | --- | --- | | 1 | 2 |Point { x: 1, y: 2 }| | 5 | 2 |Point { x: 5, y: 2 }| | -3 | 2 |Point { x: -3, y: 2 }|
derive
`#[derive(Debug)]` auto-generates trait code.
Debug
The `Debug` trait enables developer-facing formatting.
{:?}
`{:?}` prints the derived debug representation.
Exercise: derive_debug.rs
Reproduce Point { x: 1, y: 2 }, then use the pinned x variants 5 and -3 to predict Point { x: 5, y: 2 } and Point { x: -3, y: 2 }.