Course › Week 2 · Errors, collections, traits › Day 4 · lesson 11 of 42 · 25 min reading + 60–90 min practice
Generics and traits
Write code once for many types, and traits as interfaces you can implement for any type.
On this page
Two ideas today. Generics let one function or struct work for many types. Traits describe what a type can do, the way a PHP interface does. They meet in the middle: a generic function says which traits its types must have.
By the end, your error enum from yesterday prints itself with {} like every standard error, which is what tomorrow’s thiserror automates.
1. A generic function
<T> after the name declares a type parameter: “this works for any type, call it T”. The compiler makes one copy of the function for each type you actually use, so it is as fast as writing each by hand.
fn last<T>(items: &[T]) -> Option<&T> {
if items.is_empty() {
return None;
}
Some(&items[items.len() - 1])
}
fn main() {
let nights: Vec<u32> = vec![3, 7, 2];
let guests: Vec<&str> = vec!["Lina", "Omar"];
let empty: Vec<u64> = Vec::new();
println!("{:?}", last(&nights));
println!("{:?}", last(&guests));
println!("{:?}", last(&empty));
}
Some(2)
Some("Omar")
Noneitems[items.len() - 1] is safe here because the line above returned for an empty list: the “guaranteed by the code” case from yesterday’s table. (The standard library has this already: items.last().)
2. A bound says what T must be able to do
last only moved values around. A function that compares values needs to know that T can be compared. Without saying so, it does not compile:
fn largest<T>(items: &[T]) -> Option<&T> {
let mut best = items.first()?;
for item in items {
if item > best {
best = item;
}
}
Some(best)
}
fn main() {
println!("{:?}", largest(&[3, 14, 7]));
}
error[E0369]: binary operation `>` cannot be applied to type `&T`
--> src/main.rs:4:17
|
4 | if item > best {
| ---- ^ ---- &T
| |
| &T
|
help: consider restricting type parameter `T` with trait `PartialOrd`
|
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> Option<&T> {
| ++++++++++++++++++++++
For more information about this error, try `rustc --explain E0369`.
error: could not compile `hello` (bin "hello") due to 1 previous errorThe help: gives the fix: T: PartialOrd. That is a trait bound: “any type, as long as it implements the trait PartialOrd”, the standard trait behind < and >.
fn largest<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut best = items.first()?;
for item in items {
if item > best {
best = item;
}
}
Some(best)
}
fn main() {
println!("{:?}", largest(&[3, 14, 7]));
println!("{:?}", largest(&["Odense", "Aarhus", "Copenhagen"]));
}
Some(14)
Some("Odense")3. A generic struct
Structs take type parameters too. One Page<T> serves a page of bookings, of log lines, of anything, like Laravel’s paginator:
struct Page<T> {
items: Vec<T>,
total: u64,
}
impl<T> Page<T> {
fn has_more(&self) -> bool {
(self.items.len() as u64) < self.total
}
}
fn main() {
let page = Page {
items: vec!["Lina", "Omar"],
total: 41,
};
println!(
"{} of {}, more: {}",
page.items.len(),
page.total,
page.has_more()
);
}
2 of 41, more: trueimpl<T> Page<T> reads “for any T, here are the methods of Page<T>”. as u64 converts the usize length: a usize always fits in a u64 on the 64-bit machines this runs on, and there is no u64::from for usize, so as is the right tool here.
4. A trait is an interface
A trait lists methods a type must provide. impl Trait for Type provides them. One trait, two unrelated types:
trait Summary {
fn summary(&self) -> String;
}
struct Booking {
guest: String,
nights: u32,
}
struct LogEntry {
level: String,
message: String,
}
impl Summary for Booking {
fn summary(&self) -> String {
format!("{} for {} nights", self.guest, self.nights)
}
}
impl Summary for LogEntry {
fn summary(&self) -> String {
format!("[{}] {}", self.level, self.message)
}
}
fn main() {
let booking = Booking {
guest: String::from("Lina"),
nights: 3,
};
let entry = LogEntry {
level: String::from("ERROR"),
message: String::from("Payment failed"),
};
println!("{}", booking.summary());
println!("{}", entry.summary());
}
Lina for 3 nights
[ERROR] Payment failedThis is interface Summary { public function summary(): string; } with class Booking implements Summary. One difference is big: in Rust you can implement your own trait for a type you did not write, even u32 or String. PHP cannot add an interface to a class it does not own.
5. A default method
A trait can give a method a body. Every type gets it for free and can still replace it, like a method in a PHP trait or abstract class:
trait Summary {
fn summary(&self) -> String;
fn short(&self) -> String {
let full = self.summary();
match full.char_indices().nth(20) {
Some((cut, _)) => format!("{}…", &full[..cut]),
None => full,
}
}
}
struct LogEntry {
message: String,
}
impl Summary for LogEntry {
fn summary(&self) -> String {
self.message.clone()
}
}
fn main() {
let entry = LogEntry {
message: String::from("SQLSTATE[40001]: Serialization failure: 1213 Deadlock"),
};
println!("{}", entry.short());
}
SQLSTATE[40001]: Ser…char_indices().nth(20) finds the byte position of the 21st character, so the cut never falls inside a multi-byte letter (Day 4’s panic). clone() here because summary must return a new String while the entry keeps its own.
6. Accepting any type with a trait
A parameter of type &impl Summary accepts a reference to any type that implements Summary. It is short for a generic with a bound, and both forms mean the same thing:
trait Summary {
fn summary(&self) -> String;
}
struct Booking {
guest: String,
}
impl Summary for Booking {
fn summary(&self) -> String {
format!("booking for {}", self.guest)
}
}
fn notify(item: &impl Summary) {
println!("Slack: {}", item.summary());
}
fn notify_generic<T: Summary>(item: &T) {
println!("Email: {}", item.summary());
}
fn main() {
let booking = Booking {
guest: String::from("Omar"),
};
notify(&booking);
notify_generic(&booking);
}
Slack: booking for Omar
Email: booking for OmarUse impl Trait for a simple parameter. Use the <T: Trait> form when two parameters must be the same type, or when the bound gets long.
7. Display: what {} prints
{} works for any type that implements the standard trait std::fmt::Display. Implementing it for your own types is the normal way to make them printable for people. Here it is for yesterday’s error enum:
use std::fmt;
use std::io;
enum LogError {
Open { path: String, source: io::Error },
Read { line: u64, source: io::Error },
}
impl fmt::Display for LogError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
LogError::Open { path, source } => write!(f, "cannot open {path}: {source}"),
LogError::Read { line, source } => write!(f, "line {line}: {source}"),
}
}
}
fn main() {
let errors = [
LogError::Open {
path: String::from("laravel.log"),
source: io::Error::from(io::ErrorKind::NotFound),
},
LogError::Read {
line: 1812,
source: io::Error::from(io::ErrorKind::InvalidData),
},
];
for error in &errors {
println!("logstat: {error}");
}
}
logstat: cannot open laravel.log: entity not found
logstat: line 1812: invalid datawrite! is format! that writes into the formatter f instead of returning a String. The signature of fmt is fixed by the trait; copy it as it is.
Every standard error type implements Display. That is why {error} printed a sentence for io::Error and ParseIntError all week.
8. derive: the common traits, written for you
Some traits are so mechanical that the compiler writes them on request. Without them, even == on your own enum does not compile:
enum Level {
Info,
Error,
}
fn main() {
let level = Level::Error;
if level == Level::Info {
println!("just info");
}
}
error[E0369]: binary operation `==` cannot be applied to type `Level`
--> src/main.rs:8:14
|
8 | if level == Level::Info {
| ----- ^^ ----------- Level
| |
| Level
|
note: an implementation of `PartialEq` might be missing for `Level`
--> src/main.rs:1:1
|
1 | enum Level {
| ^^^^^^^^^^ must implement `PartialEq`
help: consider annotating `Level` with `#[derive(PartialEq)]`
|
1 + #[derive(PartialEq)]
2 | enum Level {
|
For more information about this error, try `rustc --explain E0369`.
error: could not compile `hello` (bin "hello") due to 1 previous erroruse std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Level {
Info,
Error,
}
fn main() {
let levels = [Level::Error, Level::Info, Level::Error];
let mut counts: HashMap<Level, u64> = HashMap::new();
for level in levels {
*counts.entry(level).or_insert(0) += 1;
}
let first = levels[0]; // Copy: levels keeps its own
println!("{first:?} seen {} times", counts[&first]);
println!("equal: {}", Level::Error == first);
}
Error seen 2 times
equal: trueWhat each derive gives you
| derive | Gives you | Needed for |
|---|---|---|
Debug | {:?} | Printing while debugging, test failure messages |
Clone | .clone() | Explicit copies |
Copy | Copied on assignment instead of moved (Day 3) | Small values: only if every field is Copy |
PartialEq, Eq | == and != | Comparisons, assert_eq! in tests |
Hash | Can be hashed | Being a HashMap key (together with Eq) |
PartialOrd, Ord | <, >, sorting | sort(), BTreeMap keys |
Coming from PHP
PHP has interfaces, and generics only in docblocks, checked by PHPStan if you run it:
<?php
interface Summary
{
public function summary(): string;
}
/** @template T */
final class Page
{
/** @param list<T> $items */
public function __construct(public array $items, public int $total) {}
}
$page = new Page(['Lina', 42, null], 41); // PHP runs it; only PHPStan would object
A Rust generic is checked by the compiler and compiled to code specialised for each type, so it costs nothing at runtime. A trait is an interface you can also implement for types you did not write, and derive covers what PHP gives every object implicitly (==, var_dump, clone), but only when you ask.
PracticeThe Book ch. 10.1–10.2, Rustlings generics and traits
Read chapter 10.1 and 10.2 of the Book.
In Rustlings: 14_generics, 15_traits, then go back to 13_error_handling 5 and 6, and quiz3.
Exercise: Display for money
Write struct Money { cents: u64 } and implement Display so that Money { cents: 45_030 } prints as €450.30 and Money { cents: 5 } as €0.05. Integer division and % only, no floats. {:02} pads a number to two digits.
Show the solution
use std::fmt;
struct Money {
cents: u64,
}
impl fmt::Display for Money {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "€{}.{:02}", self.cents / 100, self.cents % 100)
}
}
fn main() {
for cents in [45_030, 5, 100] {
println!("{}", Money { cents });
}
}
€450.30
€0.05
€1.00Remember
- A bound like
T: PartialOrdsays what a generic type must be able to do; the compiler tells you which one is missing. - Implement
Displayfor anything a person reads;derivethe mechanical traits (Debug,PartialEq,Hash…).
Tomorrow: lifetimes, explained just enough to read them, and tests with cargo test.