WeCodeAcademy

Rust derive, Default and Display

Many traits can be implemented automatically with #[derive(...)]. Implement Display yourself to control how a type prints with {}.

ExampleRust
use std::fmt;

#[derive(Debug, Clone, PartialEq, Default)]
struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = a.clone();
    println!("{}", a);
    println!("{:?}", a);
    println!("{}", a == b);
    println!("{:?}", Point::default());
    println!("{:#?}", a);
}
Output
(1, 2)
Point { x: 1, y: 2 }
true
Point { x: 0, y: 0 }
Point {
    x: 1,
    y: 2,
}
Quick check

Which trait lets a type print with {}?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.