RRust By Example
beginnerTraits

Derive Macros

Automatically implement common traits with derive.

Derive Macros

Automatically implement common traits with derive.

Difficulty

Beginner

Code

rust
#[derive(Debug, Clone, PartialEq)]
struct Color {
    r: u8,
    g: u8,
    b: u8,
}

fn main() {
    let red = Color { r: 255, g: 0, b: 0 };
    let red2 = red.clone();
    println!("{:?}", red);
    println!("equal: {}", red == red2);
}

Explanation

#[derive(...)] auto-implements common traits.

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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Traits Examples