RustTraits & Generics
Defining Traits
Traits describe shared behaviour: a method set that any type can sign up to implement. Think interfaces, the Rust dialect.
Basic Trait
rust
trait Summary { fn summarize(&self) -> String;}
struct Article { title: String, author: String, content: String,}
impl Summary for Article { fn summarize(&self) -> String { format!("{} by {}", self.title, self.author) }}
let article = Article { title: String::from("Rust 2024"), author: String::from("Ferris"), content: String::from("..."),};println!("{}", article.summarize());Default Implementations
Traits can provide default method bodies:
rust
trait Summary { fn summarize_author(&self) -> String;
fn summarize(&self) -> String { format!("(Read more from {}...)", self.summarize_author()) }}
impl Summary for Article { fn summarize_author(&self) -> String { self.author.clone() } // summarize() uses the default implementation}Key Concept
Default implementations let you bolt new methods onto a trait without breaking everyone who already implemented it. That's how Rust's standard library grows: new methods land on existing traits, defaults included, and old code keeps compiling.
Traits as Parameters
rust
fn notify(item: &impl Summary) { println!("Breaking news: {}", item.summarize());}Anything that implements Summary slots straight in.
Multiple Traits
rust
use std::fmt::Display;
fn notify(item: &(impl Summary + Display)) { println!("{}: {}", item, item.summarize());}Common Standard Library Traits
| Trait | Purpose | Example |
|---|---|---|
Display | User-facing string formatting | format!("{}", x) |
Debug | Developer-facing formatting | format!("{:?}", x) |
Clone | Explicit duplicate (the type decides how deep) | x.clone() |
Copy | Implicit copy (stack types) | let y = x; |
PartialEq | Equality comparison | x == y |
PartialOrd | Ordering comparison | x < y |
Iterator | Iteration | for x in iter |
From/Into | Type conversion | String::from("hello") |
Deriving Traits
For the common traits, Rust will write the implementation for you:
rust
#[derive(Debug, Clone, PartialEq)]struct Point { x: f64, y: f64,}
let p = Point { x: 1.0, y: 2.0 };println!("{:?}", p); // Debuglet p2 = p.clone(); // Cloneassert_eq!(p, p2); // PartialEqVersion below derives its comparisons and writes Display by hand. Derived ordering compares fields from top to bottom, so the field order matters.
Try itPredict the sorted order (1.10 versus 1.2 trips up string sorting), then move patch above major in the struct and run it again.
Rust (1.40.0)