RRust By Example
intermediateTraits

Implementing Display

Implement the Display trait for custom types.

Implementing Display

Implement the Display trait for custom types.

Difficulty

Intermediate

Code

rust
use std::fmt;

struct Color {
    r: u8,
    g: u8,
    b: u8,
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }
}

impl fmt::Debug for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Color(r={}, g={}, b={})", self.r, self.g, self.b)
    }
}

fn main() {
    let red = Color { r: 255, g: 0, b: 0 };
    println!("Display: {}", red);
    println!("Debug: {:?}", red);
    println!("format: {}", format!("color is {}", red));
}

Explanation

Implement Display for {} formatting.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

More Traits Examples