Lecture 29 - Traits: shared behavior across types
Announcements
Learning objectives
By the end of today, you should be able to:
- Define a trait and implement it for your own types
- Use a default method, and know when to override it
- Explain what
#[derive(Debug)]has been doing all this time - Implement
Ordso your own type can be sorted - Hold values of different types in one
VecwithBox<dyn Trait>
One button, many effects
Many headphones have a physical pause/play button for convenience - but how does it work?
- You're listening to music on Spotify... the button pauses the music
- You're listening to a podcast on a podcast app... the button pauses that
- You're watching a YouTube video... the pause button stops both video and audio
How do the headphones know how to pause all three?
The headphones don't know, they just send the message: "Pause!"
Each app wrote its own way to respond to that command.
We call that agreement to implement a command (or commands) a "trait".
The problem: the same job, written twice
A Player and a Team. We want to print a card for each:
struct Player { name: String, number: u32, team: String }
struct Team { name: String, wins: u32, losses: u32 }
fn describe_player(p: &Player) -> String {
format!("#{} {}, {}", p.number, p.name, p.team)
}
fn describe_team(t: &Team) -> String {
format!("{} ({}-{})", t.name, t.wins, t.losses)
}
Two functions with similar jobs.
Add a Coach, a Stadium, a Season, and now we have five functions to remember.
A trait is the promise
trait Describe {
fn describe(&self) -> String;
}
This says: any type that implements Describe has a describe method that borrows the value and returns a String.
There's no body. The trait says what the method looks like. Each type says how.
From other languages: this is an interface in Java, a protocol in Swift, an abstract base class in Python.
How each type keeps its promise
impl Describe for Player {
fn describe(&self) -> String {
format!("#{} {}, {}", self.number, self.name, self.team)
}
}
impl Describe for Team {
fn describe(&self) -> String {
format!("{} ({}-{})", self.name, self.wins, self.losses)
}
}
impl Describe for Player: "here is how a Player describes itself."
Same shape as the impl Player { } blocks we've been writing since the structs lecture, with the trait's name added.
Same bodies as before. The difference is that both methods now have the same name, under the same promise.
One function, any type that keeps the promise
struct Player { name: String, number: u32, team: String } struct Team { name: String, wins: u32, losses: u32 } trait Describe { fn describe(&self) -> String; } impl Describe for Player { fn describe(&self) -> String { format!("#{} {}, {}", self.number, self.name, self.team) } } impl Describe for Team { fn describe(&self) -> String { format!("{} ({}-{})", self.name, self.wins, self.losses) } } fn print_card(item: &impl Describe) { println!("{}", item.describe()); } fn main() { let messi = Player { name: String::from("Messi"), number: 10, team: String::from("Inter Miami") }; let miami = Team { name: String::from("Inter Miami"), wins: 22, losses: 4 }; print_card(&messi); print_card(&miami); }
&impl Describe reads as "a reference to anything that implements Describe." The function doesn't care which type it got. It only calls describe.
Activity 29, Problem 1: implement a trait on paper
Describe is the trait from the last slide. Write the impl so the program prints a 20-sided die.
struct Die { sides: u32 }
// your impl here
fn main() {
let d20 = Die { sides: 20 };
print_card(&d20);
}
Answer.
impl Describe for Die {
fn describe(&self) -> String {
format!("a {}-sided die", self.sides)
}
}
Default methods: the trait itself does some of the work
Project 3 revolves around one trait. Abridged from src/agent.rs:
trait Agent {
fn name(&self) -> String;
fn choose_move(&self, board: &Board) -> Position;
fn is_human(&self) -> bool {
false
}
}
Two methods have no body, so every new agent has to write their own.
One method with a body: is_human. That's a default method, but it can still be overridden.
Two agents from that outline
struct FirstMove;
struct Random;
impl Agent for FirstMove {
fn name(&self) -> String {
String::from("FirstMove")
}
fn choose_move(&self, board: &Board) -> Position {
board.moves()[0]
}
}
impl Agent for Random {
fn name(&self) -> String {
String::from("Random")
}
fn choose_move(&self, board: &Board) -> Position {
// pick any legal move
}
}
Neither one writes is_human (so both give false by default).
Your agent for checkpoint 2 is one more impl Agent for block.
Activity 29, Problem 2: defaults, on paper
What does this print? Then add a Safety (worth 2 points) that uses the default label.
trait Scorer {
fn points(&self) -> u32;
fn label(&self) -> String {
format!("{} points", self.points())
}
}
struct Touchdown;
struct FieldGoal;
impl Scorer for Touchdown {
fn points(&self) -> u32 { 6 }
}
impl Scorer for FieldGoal {
fn points(&self) -> u32 { 3 }
fn label(&self) -> String { String::from("three, kicked") }
}
fn main() {
println!("{}", Touchdown.label());
println!("{}", FieldGoal.label());
}
Answer. It prints 6 points, then three, kicked. Touchdown never wrote label, so it gets the default from the trait.
struct Safety;
impl Scorer for Safety {
fn points(&self) -> u32 { 2 }
}
We've been using traits since September
#[derive(Debug)]
struct Card { rank: u32, suit: char }
println!("{:?}", card);
{:?} only works on types that implement a trait called Debug. #[derive(Debug)] has been implementing it for you.
Same for .clone(), ==, <, and {}. Each one is a trait. Let's look at what we've been deriving.
Debug is a trait
trait Debug {
fn fmt(&self, f: &mut Formatter) -> Result;
}
That's it! That's the Debug trait.
Here it is written by hand, for an enum:
use std::fmt;
enum Suit { Hearts, Diamonds, Clubs, Spades }
impl fmt::Debug for Suit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Suit::Hearts => write!(f, "Hearts"),
Suit::Diamonds => write!(f, "Diamonds"),
Suit::Clubs => write!(f, "Clubs"),
Suit::Spades => write!(f, "Spades"),
}
}
}
println!("{:?}", Suit::Hearts); // Hearts
#[derive(Debug)] writes exactly this for you. You almost never write it yourself.
Display is the one you write yourself
Display is Debug's cousin, for printing with just {}. Here's the whole trait:
trait Display {
fn fmt(&self, f: &mut Formatter) -> Result;
}
Same method, same signature. {:?} calls Debug's fmt, and {} calls Display's.
There's no derive for Display, because Rust can't guess what a user should see:
use std::fmt; #[derive(Debug)] enum Suit { Hearts, Diamonds, Clubs, Spades } impl fmt::Display for Suit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let symbol = match self { Suit::Hearts => "♥", Suit::Diamonds => "♦", Suit::Clubs => "♣", Suit::Spades => "♠", }; write!(f, "{}", symbol) } } fn main() { let s = Suit::Hearts; println!("{:?}", s); // Hearts println!("{}", s); // ♥ }
Debug,{:?}: for you, while debugging. You typically derive itDisplay,{}: for the user. You typically write it (or skip it)
Clone and PartialEq are also traits
trait Clone {
fn clone(&self) -> Self;
}
trait PartialEq {
fn eq(&self, other: &Self) -> bool;
}
Both are derivable with the defaults you'd expect:
#[derive(Debug, Clone, PartialEq)]
struct Card { rank: u32, suit: char }
let a = Card { rank: 7, suit: 'h' };
let b = a.clone(); // Clone
println!("{}", a == b); // PartialEq: true
Derived PartialEq compares field by field. Derived Clone clones field by field.
So what does #[derive(...)] do?
It's a macro: code that writes code. The compiler generates an impl block for each trait you name.
// What you write:
#[derive(Debug, Clone, PartialEq)]
struct Card { rank: u32, suit: char }
// What the compiler writes for you:
impl Debug for Card { /* fmt, printing each field */ }
impl Clone for Card {
fn clone(&self) -> Self {
Card { rank: self.rank.clone(), suit: self.suit.clone() }
}
}
impl PartialEq for Card {
fn eq(&self, other: &Self) -> bool {
self.rank == other.rank && self.suit == other.suit
}
}
Sorting is a trait too
#[derive(Debug)] struct Striker { name: String, goals: u32 } fn main() { let mut scores = vec![31, 7, 24, 14]; scores.sort(); println!("{:?}", scores); let mut names = vec![String::from("Messi"), String::from("Haaland"), String::from("Mbappé")]; names.sort(); println!("{:?}", names); let mut strikers = vec![ Striker { name: String::from("Messi"), goals: 20 }, Striker { name: String::from("Haaland"), goals: 27 }, Striker { name: String::from("Mbappé"), goals: 31 }, ]; strikers.sort(); println!("{:?}", strikers); }
error[E0277]: the trait bound `Striker: Ord` is not satisfied
Numbers sort. Strings sort, alphabetically. Strikers don't (yet).
sort only works on types that implement a trait called Ord, and we haven't told Rust how to put two strikers in order. (By name? By goals?)
When the compiler says "the trait Ord is not satisfied," it's telling you you need to implement Ord to get it to work.
Ord is a trait
trait Ord {
fn cmp(&self, other: &Self) -> Ordering;
}
enum Ordering { Less, Equal, Greater }
cmp means you compare yourself to another value of the same type, and answer with one of three variants.
7.cmp(&12) // Less
String::from("Messi").cmp(&String::from("Haaland")) // Greater
sort calls cmp on pairs of elements until everything's in order. That's all it needs from a type.
We could derive it. Derived Ord compares field by field, in the order the fields are declared, so strikers would sort by name. We want goals, so we'll write it ourselves.
Activity 29, Problem 3: implement Ord on paper
Write impl Ord for Striker so that strikers.sort() puts the fewest goals first. u32 already knows how to cmp.
Ord needs Eq too, which is like PartialEq but also needs every value to equal itself.
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
struct Striker { name: String, goals: u32 }
// your impl Ord here
// Rust also wants PartialOrd. It just asks Ord:
impl PartialOrd for Striker {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
If you have time: what one change puts the most goals first?
Answer.
impl Ord for Striker {
fn cmp(&self, other: &Self) -> Ordering {
self.goals.cmp(&other.goals)
}
}
The body hands the job to u32's own cmp. Writing it out with if self.goals < other.goals { Ordering::Less } ... works too. For most goals first, swap the two sides: other.goals.cmp(&self.goals).
One collection, several types
Project 3 will end with a tournament where everyone submits a player agent and they all play each other.
To do that, we need one big vec holding agents that are of different types:
struct Random;
struct Minimax { depth: u32 }
let field = vec![Random, Minimax { depth: 3 }];
So what type is field?
Answer. There isn't one (and can't be). vec! needs every element to be the same type, and Random and Minimax are two different types.
Let's try the obvious...
Both types implement Agent, so let's ask for a vector of those:
trait Agent { fn name(&self) -> String; } struct Random; struct Minimax { depth: u32 } impl Agent for Random { fn name(&self) -> String { String::from("Random") } } impl Agent for Minimax { fn name(&self) -> String { format!("Minimax (depth {})", self.depth) } } fn main() { let field: Vec<Agent> = vec![Random, Minimax { depth: 3 }]; for agent in &field { println!("{}", agent.name()); } }
error[E0782]: expected a type, found a trait
help: you can add the `dyn` keyword if you want a trait object
Agent is a promise about types. Random and Minimax are the types. The compiler even hands you the keyword.
So let's take the compiler's advice?
let field: Vec<dyn Agent> = vec![Random, Minimax { depth: 3 }];
We get another error:
error[E0277]: the size for values of type `dyn Agent` cannot be known at compilation time
= help: the trait `Sized` is not implemented for `dyn Agent`
note: required by an implicit `Sized` bound in `Vec`
A Vec lays its elements out end to end, so it has to know how big one element is (even though it's on the heap). dyn Agent might be a Random with no data, a Minimax with a depth, or something custom and big.
It's the same reason a Vec<String> doesn't hold the text itself. Every string is a different length, so the Vec holds fixed-size handles that point to the heap.
So the fix is the same as it was for Vec<String>
Put the value on the heap and hold a pointer to it. A pointer has a size the compiler knows:
fn main() {
let field: Vec<Box<dyn Agent>> = vec![
Box::new(Random),
Box::new(Minimax { depth: 3 }),
];
for agent in &field {
println!("{}", agent.name());
}
}
That compiles, and the loop calls the right name() for each one. Box<dyn Agent> is a trait object: a box holding something that keeps the Agent promise.
What's inside a Box<dyn Agent>?
A Random has no fields. A Minimax has a depth. The loop called agent.name() on both and got the right answer each time. How?
The box has to carry two things:
- the data: the fields of whichever struct is in there
- the methods: which
nameand whichchoose_movego with that struct
So it holds a pointer to each. Here's one box on its own:
let agent: Box<dyn Agent> = Box::new(Minimax { depth: 3 });
Stack: Heap:
┌───────────────────────────┐
│ main() │ ┌──────────────┐
│ └ agent: Box<dyn Agent> │ │ Minimax │
│ ├ data ────────────────┼────────▶│ └ depth: 3 │
│ └ methods ─────────────┼───┐ └──────────────┘
└───────────────────────────┘ │
│ Program binary (read-only):
│ ┌───────────────────────────┐
└────▶│ Agent methods for Minimax │
│ ├ name │
│ └ choose_move │
└───────────────────────────┘
Calling agent.name() follows the methods pointer to find the right name, while the program runs. That's called dynamic dispatch.
Vec<Box<dyn Agent>> is the shape to remember. The tournament in Project 3 is round_robin(agents: &[Box<dyn Agent>], ...): 73 strategies, 73 types, one slice.
The table-of-methods picture is in the appendix at the bottom of this page.
Activity 29
See Activity 29. Problems 1 to 3 are done. Problem 4 is on a laptop: one Shape trait, two shapes, one Vec<Box<dyn Shape>>, then a third shape added without touching the loop. Answers go on Gradescope.
Appendix: three things we skipped
Trait extension
One trait can require another. Employee: Person means "to implement Employee, you must also implement Person," and Employee's default methods can call Person's methods:
trait Person {
fn get_name(&self) -> String;
}
trait Employee: Person {
fn employee_id(&self) -> u32;
fn badge(&self) -> String {
format!("{} - #{}", self.get_name(), self.employee_id())
}
}
A type implements both, in two impl blocks, the base trait first. You'll see this in the standard library: Eq: PartialEq and Ord: PartialOrd + Eq, which is why deriving Ord needs the other three.
Which traits need a use
Some traits are in the prelude, so they work without importing anything: Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Drop, Iterator. Deriving them needs no use line either.
Others have to be brought in:
use std::fmt::{Debug, Display};
use std::ops::{Add, Sub, Mul, Div};
#[derive(Debug)] works without the use because the derive macro writes the full path itself. Writing impl Display for by hand is where you first need use std::fmt.
The table of methods behind Box<dyn Agent>
┌─ Box<dyn Agent> holding a Minimax ──────┐
│ │
│ The box is two pointers │
│ ├─ data_ptr ──────────────┐ │
│ └─ vtable_ptr ────┐ │ │
└──────────────────────┼───────┼──────────┘
│ │ ┌──────────────────────────┐
│ └──▶│ Minimax { │
│ │ depth: 3, │
│ │ } │
│ └──────────────────────────┘
└─▶ vtable for Agent on Minimax (in the binary):
┌────────────────────────────────┐
│ name: 0x1234 │
│ choose_move: 0x5678 │
│ is_human: 0xABCD │
│ drop: 0xDEF0 │
└────────────────────────────────┘
When you call agent.name(): follow the vtable pointer, look up the name entry, call that function with the data pointer. The vtable is built once per (type, trait) pair when the program is compiled; only the lookup happens at run time.
That lookup is what dynamic dispatch costs: two pointer hops on every call. Wednesday's generics are the other choice.
- Trait objects (
Box<dyn Trait>): a little slower, and you can mix types in one collection - Generics: no cost per call, and every element has to be the same type