Appendix C: Derivable Traits
In this chapter, we'll explore traits that can be automatically derived.
Appendix C: Derivable Traits
The #[derive] attribute generates default implementations for certain traits. Here are the traits you can derive.
Debug
Enables formatting for debugging output:
#[derive(Debug)]
struct Point {
x: int,
y: int,
}
let p = Point { x: 1, y: 2 }
println(p.debug()) // Point { x: 1, y: 2 }Clone
Enables deep copying:
#[derive(Clone)]
struct Point {
x: int,
y: int,
}
let p1 = Point { x: 1, y: 2 }
let p2 = p1.clone()Copy
Enables bitwise copying (for simple types):
#[derive(Copy, Clone)]
struct Point {
x: int,
y: int,
}
let p1 = Point { x: 1, y: 2 }
let p2 = p1 // Copied, not moved
println(p1.x) // Still validNote: Copy requires Clone.
Eq and PartialEq
Enable equality comparison:
#[derive(PartialEq, Eq)]
struct Point {
x: int,
y: int,
}
let p1 = Point { x: 1, y: 2 }
let p2 = Point { x: 1, y: 2 }
assert(p1 == p2)Ord and PartialOrd
Enable ordering comparison:
#[derive(PartialOrd, Ord, PartialEq, Eq)]
struct Point {
x: int,
y: int,
}
let points = [
Point { x: 2, y: 1 },
Point { x: 1, y: 2 },
]
points.sort()Hash
Enable hashing (for use in hash maps):
#[derive(Hash, PartialEq, Eq)]
struct Point {
x: int,
y: int,
}
let mut map = HashMap::new()
map.insert(Point { x: 1, y: 2 }, "origin")Default
Provide default values:
#[derive(Default)]
struct Config {
debug: bool,
port: int,
}
let config = Config::default()
// debug: false, port: 0Deriving Multiple Traits
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct User {
id: int,
name: string,
}When You Can't Derive
Some types can't derive certain traits:
Eqrequires all fields implementEqCopyrequires all fields implementCopy- Types with heap data (like
String) can't beCopy
In these cases, implement the trait manually.