Sub topic 3
Common Rust Traits and `#[derive]`
Assume you know structs, ownership, borrowing, basic generics, and how to run a Cargo program. This chapter focuses on standard traits that make your types work with Rust’s existing tools.
Common traits and `#[derive]`
The Debug trait supports programmer-focused output with the {:?} formatter. Display supports user-facing output with {}. Clone creates an explicit copy, while Copy allows implicit copying for small, entirely copyable values. PartialEq enables equality comparisons.
The derive attribute generates implementations when Rust can do so mechanically:
use std::fmt;
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let point = Point { x: 1, y: 2 };
println!("{point:?}");
println!("{point}");
println!("{:?}", point + Point { x: 3, y: 4 });
}Operators and implementation rules
Traits in std::ops define operators. Implementing Add gives meaning to +; similar traits define -, *, indexing, and other operations.
Rust’s orphan rule preserves coherence: an implementation is allowed when either the trait or the type belongs to your crate. You cannot implement a foreign trait for a foreign type, such as adding your own Display implementation for Vec<i32>.
A blanket implementation applies a trait to every type meeting a bound. For example, a crate can implement a local trait for every type that implements Display. This is powerful, but broad implementations can conflict with future implementations.
`Iterator` and associated items
Iterator uses an associated type to state one item type per implementation. Implementing next provides default methods such as map, filter, and collect.
struct Countdown(u32);
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
None
} else {
let value = self.0;
self.0 -= 1;
Some(value)
}
}
}
fn main() {
let values: Vec<u32> = Countdown(3).collect();
println!("{values:?}");
}Associated constants and marker traits
A trait can declare an associated constant, such as const LIMIT: usize. Each implementation supplies its value.
Copy, Send, Sync, and Sized are marker traits. Marker traits communicate properties rather than requiring methods. Send means ownership can move between threads. Sync means shared references can be used across threads. Sized means a type has a known size at compile time and is an implicit bound unless written as ?Sized.
Exercise
Why can a local trait be implemented for a foreign type, but a foreign trait cannot be implemented for two foreign types?
Show answer
The orphan rule allows an implementation when the trait or the type is local, which keeps trait resolution coherent.