The Analogy: The Licence Category, Not The Driver
A driving licence does not describe a person. It lists categories -- B for a car, C for a lorry, D for a bus -- and each category is a promise about one specific set of things the holder can be asked to do. Nothing on the card says who the holder is, what vehicle they own, where they learned, or how long ago they passed. A haulage firm filling a lorry route does not ask about any of that. It asks for category C.
That is exactly what makes the card useful for organising work. A shift can be written as "needs category C" long before anyone knows who will take it, and the roster can then be filled from a pool of people who have nothing else whatsoever in common. Two holders of the same category might have arrived by completely different routes -- one drove army lorries for a decade, one passed the test last month -- and for the purpose of assigning that shift they are interchangeable. The card is the only thing the shift needs to know.
Categories also come with standard procedures attached. Every holder is expected to do a walk-around check before setting off, and the expected version of that check is printed in the handbook, so nobody has to invent one. A firm with its own longer check substitutes it; a firm with no opinion uses the printed one. Either way, the shift can be written on the assumption that a check happens, without specifying whose.
And here is the part that is easy to forget: the card proves a test was passed. It says nothing about whether the holder is any good. It guarantees the shape of the qualification and is entirely silent about the quality of the driving. Rust's traits are precisely this -- a named set of operations a type promises to provide, checked for shape at compile time and completely indifferent to whether the implementation does anything sensible. This lesson is about writing the categories and hiring by them. The next lesson is about sitting the test.
Syntax or Core Structure
A trait is a named list of method signatures. Some have bodies and some do not, and the difference decides who is obliged to write what:
trait Alarm {
fn severity(&self) -> u32;
fn label(&self) -> String;
fn headline(&self) -> String {
format!("[{}] {}", self.severity(), self.label())
}
}
struct Smoke {
room: String,
}
struct Battery {
percent: u32,
}
impl Alarm for Smoke {
fn severity(&self) -> u32 {
9
}
fn label(&self) -> String {
format!("smoke in {}", self.room)
}
}
impl Alarm for Battery {
fn severity(&self) -> u32 {
if self.percent < 10 {
4
} else {
1
}
}
fn label(&self) -> String {
format!("battery at {}%", self.percent)
}
fn headline(&self) -> String {
format!("battery {}% (severity {})", self.percent, self.severity())
}
}
fn main() {
let s = Smoke { room: String::from("kitchen") };
let b = Battery { percent: 6 };
println!("{}", s.headline());
println!("{}", b.headline());
println!("labels {} / {}", s.label(), b.label());
println!("severities {} {}", s.severity(), b.severity());
}
Output:
[9] smoke in kitchen
battery 6% (severity 4)
labels smoke in kitchen / battery at 6%
severities 9 4
severity and label end in a semicolon, which makes them required: every impl Alarm for ... block has to supply both, and the compiler counts. headline has a body, which makes it a default: an impl may supply its own or say nothing and inherit the one in the trait. Smoke said nothing and got [9] smoke in kitchen; Battery overrode it and got its own phrasing.
Look at what headline's default body is allowed to do. It calls self.severity() and self.label() without any idea what those bodies contain, because the trait guarantees they exist. It cannot touch self.room or self.percent, because the trait knows nothing about fields -- only about the methods it declared. A default method can use the trait's own vocabulary and nothing else.
A trait can hold five kinds of item, and all five turn up in the standard library:
| Item | Written as | Who supplies it |
|---|---|---|
| Required method | fn severity(&self) -> u32; | Every impl, always |
| Default method | fn headline(&self) -> String { ... } | The trait, unless an impl overrides |
| Associated function | fn zero() -> Self; | Every impl; called as Type::zero() |
| Associated constant | const UNIT: &'static str; | Every impl, unless the trait gives a value |
| Associated type | type Item; | Every impl; the shape behind Iterator, in Module 7 |
Technical Depth: Hiring By Capability
The vocabulary you have been using since Module 1
Traits are not a new feature arriving at this point in the course. They are the mechanism that everything so far was quietly built on, and it is worth putting names to the whole set at once:
| Trait | What it names | Where it already appeared |
|---|---|---|
Display | Formatting with {} | Every println! since Module 1 |
Debug | Formatting with {:?} | #[derive(Debug)] on structs and enums |
Clone | Making an explicit deep copy | .clone() in the ownership lesson |
Copy | Being duplicated implicitly on assignment | Why integers behave differently from String |
PartialEq and Eq | == and != | Comparing values in Module 2 |
PartialOrd and Ord | <, > and sorting | sort() on a Vec in Module 4 |
From and Into | Infallible conversion | What the ? operator calls in Module 5 |
Error | Being an error worth reporting | The boxed error type in Module 5 |
Iterator | Producing a sequence of items | Every for loop; Module 7 |
Default | Having a sensible zero value | Default::default() |
Each of those is an ordinary trait declared in the standard library with exactly the syntax above. There is no privileged category.
Hiring one and not caring which
The point of a category is that work can be assigned without knowing who will do it. In Rust the syntax for that is dyn:
trait Alarm {
fn severity(&self) -> u32;
fn label(&self) -> String;
}
struct Smoke {
room: String,
}
struct Battery {
percent: u32,
}
struct Door {
open_minutes: u32,
}
impl Alarm for Smoke {
fn severity(&self) -> u32 {
9
}
fn label(&self) -> String {
format!("smoke in {}", self.room)
}
}
impl Alarm for Battery {
fn severity(&self) -> u32 {
4
}
fn label(&self) -> String {
format!("battery at {}%", self.percent)
}
}
impl Alarm for Door {
fn severity(&self) -> u32 {
if self.open_minutes > 30 {
6
} else {
2
}
}
fn label(&self) -> String {
format!("door open {} min", self.open_minutes)
}
}
fn report(alarms: &[&dyn Alarm]) {
let mut total = 0;
for a in alarms {
println!("{:>2} {}", a.severity(), a.label());
total += a.severity();
}
println!("total severity {total}");
}
fn main() {
let s = Smoke { room: String::from("kitchen") };
let b = Battery { percent: 6 };
let d = Door { open_minutes: 45 };
let all: [&dyn Alarm; 3] = [&s, &b, &d];
report(&all);
}
Output:
9 smoke in kitchen
4 battery at 6%
6 door open 45 min
total severity 19
Three unrelated structs of three different sizes sit in one array. That is only possible because &dyn Alarm is not a reference to a Smoke or a Door -- it is a pair of pointers, one to the value and one to a table of that type's implementations of the trait's methods. Every a.severity() reads the function's address out of that table and calls it. This is dynamic dispatch, and you can see the second pointer:
fn main() {
println!("&Smoke {}", std::mem::size_of::<&Smoke>());
println!("&dyn Alarm {}", std::mem::size_of::<&dyn Alarm>());
}
Output:
&Smoke 8
&dyn Alarm 16
Those are the figures on a 64-bit target: one machine word for an ordinary reference, two for a trait object. The trade is worth stating plainly now and revisiting in the trait-bounds lesson. Dynamic dispatch gives one compiled copy of report, a heterogeneous array, and a call the optimiser cannot usually inline. Static dispatch through a generic bound gives a direct, inlinable call and a copy of report per type -- and no way at all to put three types in one array.
Not every trait can be hired anonymously
A trait usable behind dyn is called object safe, and the rules exist because a vtable has to be buildable without knowing the concrete type. Two of them account for nearly every real failure. A method that returns Self by value cannot be in the table, because the caller would not know how big the result is. A method with its own generic parameter cannot be in the table either, because there is one table and there would need to be one entry per instantiation.
That is why the Sensor trait below cannot be used as &dyn Sensor -- zero returns Self. The error is E0038, and it says the trait cannot be made into an object and names the offending method. The usual fix is to split the trait: put the constructor in one trait and the object-safe operations in another.
trait Sensor {
const UNIT: &'static str;
fn zero() -> Self;
fn reading(&self) -> f64;
fn describe(&self) -> String {
format!("{:.1} {}", self.reading(), Self::UNIT)
}
}
struct Thermometer {
celsius: f64,
}
impl Sensor for Thermometer {
const UNIT: &'static str = "C";
fn zero() -> Self {
Thermometer { celsius: 0.0 }
}
fn reading(&self) -> f64 {
self.celsius
}
}
fn main() {
let cold = Thermometer::zero();
let warm = Thermometer { celsius: 21.5 };
println!("cold {}", cold.describe());
println!("warm {}", warm.describe());
println!("unit {}", Thermometer::UNIT);
}
Output:
cold 0.0 C
warm 21.5 C
unit C
zero has no self parameter, so it is an associated function called as Thermometer::zero() rather than a method. UNIT is an associated constant, reachable from the default method as Self::UNIT and from outside as Thermometer::UNIT. Both are ordinary trait items; both are the reason this trait is not object safe.
Categories that require other categories
A trait may require another trait of anything that implements it. That prerequisite is called a supertrait, and it makes the required trait's methods available inside default bodies:
trait Named {
fn name(&self) -> String;
}
trait Alarm: Named {
fn severity(&self) -> u32;
fn headline(&self) -> String {
format!("{} at severity {}", self.name(), self.severity())
}
}
struct Smoke;
struct Door;
impl Named for Smoke {
fn name(&self) -> String {
String::from("smoke")
}
}
impl Alarm for Smoke {
fn severity(&self) -> u32 {
9
}
}
impl Named for Door {
fn name(&self) -> String {
String::from("door")
}
}
impl Alarm for Door {
fn severity(&self) -> u32 {
6
}
}
fn main() {
let all: [&dyn Alarm; 2] = [&Smoke, &Door];
for a in all {
println!("{}", a.headline());
}
}
Output:
smoke at severity 9
door at severity 6
trait Alarm: Named reads as "anything that is an Alarm must also be Named". Writing impl Alarm for Smoke without the impl Named for Smoke block is a trait-bound error, not a missing-method error, and the message names Named directly. Use a supertrait for a genuine prerequisite -- an alarm has to be identifiable before a report can list it -- and not as a way to bundle two unrelated capabilities into one requirement.
Real World Example: One Notification Pipeline, Four Channels
An operations service has to push the same alert out over email, SMS, a pager and the local log. The sequence is identical every time -- shorten the message to whatever the channel can carry, hand it over, report what happened -- and only the last step and the size limit differ. That shape is exactly what a trait with default methods is for.
trait Channel {
fn name(&self) -> &'static str;
fn max_chars(&self) -> usize;
fn deliver(&self, text: &str) -> Result<usize, String>;
fn fit(&self, text: &str) -> String {
let limit = self.max_chars();
if text.chars().count() <= limit {
return String::from(text);
}
let mut out = String::new();
for (i, c) in text.chars().enumerate() {
if i + 3 >= limit {
break;
}
out.push(c);
}
out.push_str("...");
out
}
fn send(&self, text: &str) -> String {
let body = self.fit(text);
match self.deliver(&body) {
Ok(n) => format!("{:<6} sent {} chars", self.name(), n),
Err(e) => format!("{:<6} failed: {}", self.name(), e),
}
}
}
struct Email {
address: String,
}
struct Sms {
number: String,
credit: u32,
}
struct Pager {
id: u32,
}
struct Console;
impl Channel for Email {
fn name(&self) -> &'static str {
"email"
}
fn max_chars(&self) -> usize {
500
}
fn deliver(&self, text: &str) -> Result<usize, String> {
if !self.address.contains('@') {
return Err(format!("{} is not an address", self.address));
}
Ok(text.len())
}
}
impl Channel for Sms {
fn name(&self) -> &'static str {
"sms"
}
fn max_chars(&self) -> usize {
30
}
fn deliver(&self, text: &str) -> Result<usize, String> {
if self.credit == 0 {
return Err(format!("no credit for {}", self.number));
}
Ok(text.len())
}
}
impl Channel for Pager {
fn name(&self) -> &'static str {
"pager"
}
fn max_chars(&self) -> usize {
12
}
fn deliver(&self, text: &str) -> Result<usize, String> {
if self.id == 0 {
return Err(String::from("pager id 0 is not assigned"));
}
Ok(text.len())
}
fn fit(&self, text: &str) -> String {
let mut out = String::new();
let mut n = 0;
for c in text.chars() {
if n == self.max_chars() {
break;
}
out.push(c);
n += 1;
}
out
}
}
impl Channel for Console {
fn name(&self) -> &'static str {
"log"
}
fn max_chars(&self) -> usize {
usize::MAX
}
fn deliver(&self, text: &str) -> Result<usize, String> {
Ok(text.len())
}
}
fn broadcast(channels: &[&dyn Channel], text: &str) {
for c in channels {
println!("{}", c.send(text));
}
}
fn main() {
let email = Email { address: String::from("ops@example.com") };
let broken = Email { address: String::from("ops.example.com") };
let sms = Sms { number: String::from("07700900123"), credit: 5 };
let flat = Sms { number: String::from("07700900124"), credit: 0 };
let pager = Pager { id: 41 };
let console = Console;
let all: [&dyn Channel; 6] = [&email, &broken, &sms, &flat, &pager, &console];
broadcast(&all, "disk 3 in rack 12 is at 94 percent");
}
Output:
email sent 34 chars
email failed: ops.example.com is not an address
sms sent 30 chars
sms failed: no credit for 07700900124
pager sent 12 chars
log sent 34 chars
broadcast is nine lines long and mentions no channel. It takes a slice of things that can be sent to, and sends to them. Adding a fifth channel type is one impl Channel for ... block and one more element in the array; broadcast does not change, is not recompiled differently, and cannot forget the new channel, because it never enumerated the old ones. That is the whole return on writing the category down.
The default methods carry more weight here than the required ones. fit and send are written once in the trait and inherited by all four types, and between them they own the sequence: shorten, hand over, report. Each impl owns one step of it. Pager is the only type that overrode fit, and for a good reason -- on a twelve-character display, spending three of them on an ellipsis is worse than losing three characters of the message. Every other channel took the printed procedure.
&[&dyn Channel] is what makes the heterogeneous array legal. Six values of four different sizes, some holding a String and one holding nothing at all, all reduced to identical two-word handles with a vtable pointer alongside. There is one compiled copy of broadcast and one of send, and every c.send(text) is an indirect call. The generic-bound version in two lessons' time is faster per call and could not hold this array; for six notifications the difference is unmeasurable, and for six million it would not be.
Four honest limits, and the first is a design error rather than a rough edge. name() is a method on the type, so both Email values report email and the output cannot tell the working address from the broken one -- identity belongs on the instance, and putting it in the trait made it unavailable. deliver fails with a String, which Module 5 already established as the error type that cannot be inspected, so no caller can retry only the transient failures. fit counts characters while deliver reports text.len(), which is bytes, so sent 30 chars is a lie for any message containing a non-ASCII character and the trait's own vocabulary is inconsistent with itself. And nothing here performs any I/O at all: a real channel returns a network error, needs a timeout, a retry policy and some idea of whether re-sending is safe, and none of that is anywhere in this shape.
Common Mistakes
- Giving a required method an empty body instead of a semicolon.
fn deliver(&self) {}is a default method that silently does nothing, and every impl will happily inherit it. The semicolon is what makes the compiler insist.
- Believing a trait guarantees behaviour. It guarantees signatures.
impl PartialOrdthat reports every value as less than every other compiles perfectly, and the type is now broken in every sorted collection in the program.
- Calling a trait method with the trait not in scope. The error says items from traits can only be used if the trait is in scope, and the fix is a
useline, not a change to the type.
- Reaching for
&dyn Traiton a trait that returnsSelfor has a generic method.E0038says the trait cannot be made into an object. Split the trait rather than fighting it.
- Expecting a default method to read fields. A default body can only call the trait's own methods. If it needs a value, the trait needs a method that returns that value.
- Overriding a default and breaking what the other defaults assumed.
Pager::fitis a deliberate example: it drops the ellipsis, so anything downstream that inferred truncation from the trailing dots is now wrong.
- Storing a
&dyn Traitin a struct without saying how long it lives. The field needs a lifetime parameter, and if the answer is "the struct owns it" then what you wanted wasBox<dyn Trait>, which is Module 8.
- Assuming dynamic dispatch is free, or that generics can replace it. Each
dyncall is a table lookup and usually not inlined; each generic instantiation is another compiled copy and cannot share an array with a different type. They are two different tools.
- Declaring a supertrait and forgetting to implement it. The error is a trait-bound failure naming the supertrait, which reads confusingly if you have forgotten that the colon in
trait Alarm: Namedwas a requirement.
Best Practices
- Name the capability, not the family of types.
ChannelandAlarmdescribe what can be done;EmailLikedescribes what something resembles, and nothing useful can be built on a resemblance.
- Keep the required set as small as it can be and build everything else as defaults. Each required method is a line every future implementor has to write, forever.
- Put the sequence in the trait and the step in the impl. If four impls all repeat the same three calls in the same order, that order belongs in a default method.
- Design for object safety unless you have a reason not to. Avoiding
-> Selfand generic methods costs almost nothing up front and keepsdynavailable later.
- Use
dynfor heterogeneous collections, plugin-style extension points and anything where code size matters more than call overhead. Use bounds for the hot path.
- Reserve supertraits for genuine prerequisites. Bundling unrelated capabilities behind one colon forces implementors to satisfy requirements they have no use for.
- Write down, in a comment or a doc line, the semantics the signatures cannot enforce -- that
delivermust not panic, thatmax_charsmust not change between calls. The compiler will never check these, and the next implementor will never guess them.
- Keep per-instance data out of per-type methods. A method with no way to vary between two values of the same type cannot carry anything that distinguishes them.
Practice Exercises
- Add a
Webhookchannel with a 2000-character limit that fails when its URL does not start withhttps. Then count exactly how many existing lines you had to change, and say what that number would have been for a design built on amatchover a channel enum.
- Fix the identity problem. Change
Channelso the report can distinguish the workingEmailfrom the broken one, and say which of the two obvious approaches -- a new required method, or including the address in the error -- you chose and why.
- Add
fn preferred() -> Self;toChannel, try to keep the[&dyn Channel; 6]array, and read the error. Then split the trait so that both the constructor and the array survive, and write down which methods ended up in which trait.
- Make
fitand the report agree. Decide whether the pipeline works in characters or in bytes, change both sides to match, and then say what breaks if a message arrives containing an emoji.