Rust 1.99 (2024 edition) reference · Traits and Smart Pointers

Rust #[derive] Keyword

Generate standard trait implementations such as Debug, Clone, PartialEq, Eq, Hash, Default and PartialOrd for your types.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]

Parameters

ParameterDescription
Debug {:?} formatting.
Clone / Copy Explicit / implicit copies.
PartialEq / Eq / Hash Comparison and use as HashMap keys.
Default Type::default().
PartialOrd / Ord Ordering, compared field by field.

Examples

Example 1
use std::collections::HashSet;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
struct Version { major: u32, minor: u32 }

fn main() {
    let a = Version { major: 1, minor: 99 };
    let b = Version { major: 2, minor: 0 };
    println!("{a:?} < {b:?}: {}", a < b);
    println!("{:?}", Version::default());
    let mut seen = HashSet::new();
    seen.insert(a.clone());
    println!("{}", seen.contains(&a));
}

Output

Version { major: 1, minor: 99 } < Version { major: 2, minor: 0 }: true
Version { major: 0, minor: 0 }
true

Run this on your computer — see “Get Started” for setup.

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

fn main() {
    let p = Point { x: 1, y: 2 };
    let q = p; // Copy: p is still usable
    println!("{p:?} {q:?} {}", p == q);
}

Output

Point { x: 1, y: 2 } Point { x: 1, y: 2 } true

Run this on your computer — see “Get Started” for setup.

Was this page helpful?