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)
Syntax
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
Parameters
| Parameter | Description |
|---|---|
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
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 }
trueRun this on your computer — see “Get Started” for setup.
#[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 } trueRun this on your computer — see “Get Started” for setup.
Related
impl Display· Implement std::fmt::Display to control how a type prints with {} and converts with to_string().From and Into· Convert between types: implement From<T> and get Into for free; ? uses From to convert error types.- Rust Structs and Methods · tutorial