A trait is a set of methods that many types can share. This part shows how to define and implement traits, what derive writes for you, how to make {} work with Display, and the orphan rule that decides who may write an impl.
A trait names something a type can do. Debug means “can be printed with {:?}“. Clone means “can make a copy of itself”. You’ve used both since Part 6, mostly through #[derive(...)]. In this part we write our own traits, implement them for our own types, and look at what derive really does.
We’ll also make {} work for a struct by writing Display by hand, meet a few standard traits you’ll see everywhere, and learn the orphan rule, which decides who is allowed to implement which trait for which type. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
Part 10 printed structs with {:?}. What happens if you use plain {}?
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 3, y: -1 };
println!("{p}");
println!("{} {}", p.x, p.y);
}
It doesn’t compile:
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--> src/main.rs:8:15
|
8 | println!("{p}");
| ^^^ `Point` cannot be formatted with the default formatter
|
help: the trait `std::fmt::Display` is not implemented for `Point`
Read the help: line. {} doesn’t print “any value”. It asks the value’s type for its Display code, and Point has none. Rust won’t guess whether a point should look like (3, -1), 3,-1 or x=3 y=-1. You have to say. By the end of this part, that program will print (3, -1).
The error code is E0277. It means “this type doesn’t implement a trait that this code needs”. It’s the error you’ll meet most often in this part.
A trait is a promise
Say we have two kinds of item in a news app, a post and a short message. We want to show a one-line summary of either one. A trait says what “can be summarised” means:
trait Summary {
fn summarize(&self) -> String;
}
struct Post {
title: String,
author: String,
}
struct Message {
user: String,
text: String,
}
impl Summary for Post {
fn summarize(&self) -> String {
format!("{}, by {}", self.title, self.author)
}
}
impl Summary for Message {
fn summarize(&self) -> String {
format!("@{}: {}", self.user, self.text)
}
}
fn main() {
let post = Post {
title: String::from("Traits in Rust"),
author: String::from("Ana"),
};
let msg = Message {
user: String::from("ben"),
text: String::from("Rust 1.95 is out"),
};
println!("{}", post.summarize());
println!("{}", msg.summarize());
}
It prints:
Traits in Rust, by Ana
@ben: Rust 1.95 is out
There are three pieces here:
- The trait definition.
trait Summary { fn summarize(&self) -> String; }lists a method’s signature, ending in;with no body. It says “a type that isSummaryhas this method”. It doesn’t say how. - The impls.
impl Summary for Post { ... }is an implementation, or impl for short. It gives the body of every method the trait lists, for one type. Each type writes its own. - The call.
post.summarize()looks like any method call from Part 10. The difference is where the method came from.
An impl Summary for Post block is a promise the compiler checks. Write impl Summary for Post {} with the method left out, and the build fails:
error[E0046]: not all trait items implemented, missing: `summarize`
If you know interfaces from Java, Go or TypeScript, a trait is close to one. One difference matters a lot below: a Rust type doesn’t list its traits where the type is defined. Each impl is a separate block, and it can live away from the type.
Default methods, and traits as parameters
A trait can give a method a body. Then every type gets that method for free, and a type can still replace it with its own. And once several types share a trait, one function can take any of them:
trait Summary {
fn summarize(&self) -> String;
fn preview(&self) -> String {
format!("{} (read more)", self.summarize())
}
}
struct Post {
title: String,
}
struct Message {
text: String,
}
impl Summary for Post {
fn summarize(&self) -> String {
self.title.clone()
}
}
impl Summary for Message {
fn summarize(&self) -> String {
self.text.clone()
}
fn preview(&self) -> String {
format!("new message: {}", self.text)
}
}
fn notify(item: &impl Summary) {
println!("Breaking! {}", item.preview());
}
fn main() {
let post = Post {
title: String::from("Traits in Rust"),
};
let msg = Message {
text: String::from("lunch?"),
};
notify(&post);
notify(&msg);
}
It prints:
Breaking! Traits in Rust (read more)
Breaking! new message: lunch?
Post wrote only summarize, so it got the default preview. That default calls self.summarize(), and for a Post that runs Post‘s own summarize. Message wrote its own preview, which replaces the default. This is a common shape: the trait asks for one or two small required methods and builds useful ones on top of them.
Now read item: &impl Summary as “a reference to some type that implements Summary“. Inside notify, you may call only what Summary promises. The function doesn’t know whether it got a Post or a Message, and it doesn’t need to. Pass it something else, such as notify(&5), and the build fails:
error[E0277]: the trait bound `{integer}: Summary` is not satisfied
{integer} is how the compiler writes “some integer type I haven’t picked yet”. A trait bound is a rule like “this type must implement Summary“, and &impl Summary is the short way to write one. Part 15 covers the longer forms, T: Summary and where, and what the compiler builds for each type you pass in. Part 21 covers dyn Summary, which lets you keep a Post and a Message in the same Vec.
derive: impls the compiler writes for you
Many traits have one obvious implementation. Two points are equal when their x and y are equal. A struct prints for debugging as its name and fields. For those, #[derive(...)] asks the compiler to write the impl. Here are the ones you can derive from the standard library:
| Trait | What you get | What it needs |
|---|---|---|
Debug |
{:?} and {:#?} printing |
every field is Debug |
Clone |
.clone(), field by field |
every field is Clone |
Copy |
assignment copies instead of moving (Part 6) | every field is Copy, and Clone too |
PartialEq |
== and !=, field by field |
every field is PartialEq |
Eq |
a promise that x == x is always true |
PartialEq, every field is Eq |
PartialOrd |
<, >, <=, >= |
PartialEq, every field is PartialOrd |
Ord |
a full order: sort, max, BTreeMap keys |
Eq, PartialOrd, every field is Ord |
Hash |
use as a HashMap key or HashSet item |
every field is Hash |
Default |
Type::default(): every field set to its default |
every field is Default |
Here’s a type with all nine:
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
struct Version {
major: u32,
minor: u32,
}
fn main() {
let a = Version {
major: 1,
minor: 95,
};
let b = a;
println!("Debug: {a:?}");
println!("Default: {:?}", Version::default());
println!("a == b: {}", a == b);
let old = Version {
major: 1,
minor: 80,
};
println!("old < a: {}", old < a);
let mut list = vec![Version { major: 2, minor: 0 }, a, old];
list.sort();
println!("sorted: {list:?}");
let mut set = HashSet::new();
for v in [a, b, old] {
set.insert(v);
}
println!("set holds: {} versions", set.len());
}
It prints:
Debug: Version { major: 1, minor: 95 }
Default: Version { major: 0, minor: 0 }
a == b: true
old < a: true
sorted: [Version { major: 1, minor: 80 }, Version { major: 1, minor: 95 }, Version { major: 2, minor: 0 }]
set holds: 2 versions
let b = a copied, because of Copy, so a is still usable. The set holds 2 versions, because a and b are equal and hash the same, so the second insert did nothing.
Notice how < and sort decided the order. A derived PartialOrd compares the first field, and looks at the next field only when the first ones are equal. That’s dictionary order, and it means the order you declare the fields in is the sort order. The worked example below uses that.
When derive is refused
A derive needs every field to have the trait too. When one field doesn’t, the compiler names it:
#[derive(Debug, PartialEq, Eq)]
struct Reading {
place: String,
celsius: f64,
}
fn main() {
let a = Reading {
place: String::from("Pune"),
celsius: 31.5,
};
println!("{a:?}");
}
It prints:
error[E0277]: the trait bound `f64: Eq` is not satisfied
...
1 | #[derive(Debug, PartialEq, Eq)]
| -- in this derive macro expansion
...
4 | celsius: f64,
| ^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64`
f64 is PartialEq, but it isn’t Eq. The float value NaN, “not a number”, isn’t equal to itself, so x == x can be false. Eq promises it never is. For the same reason, floats are PartialOrd but not Ord, and you can’t call sort() on a Vec<f64>. Drop Eq from the derive, or store something that is Eq, such as tenths of a degree in an i32.
Two other refusals you’ve seen or will see:
Copyon a struct with aStringfield is E0204 (Part 6). A type that owns heap memory can’t be copied bit by bit.Defaulton an enum is E0665 unless you mark one unit variant with#[default], because the compiler can’t pick one for you.
Display: writing an impl of a standard trait
Now we can fix the program from the start. Display is a trait in std::fmt with one required method, fmt:
use std::fmt;
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)
}
}
fn main() {
let p = Point { x: 3, y: -1 };
println!("{p}");
println!("the point is {p}");
let s = p.to_string();
println!("{s} has {} characters", s.len());
}
It prints:
(3, -1)
the point is (3, -1)
(3, -1) has 7 characters
The signature is the one in the standard library’s docs, copied exactly. Here’s what each piece means:
f: &mut fmt::Formatteris where the text goes.println!makes one for you and passes it in.write!(f, ...)works likeformat!, but it writes intofinstead of making a newString.fmt::Resultsays whether writing worked. Part 12 coveredResult.write!returns one, so making it the last expression returns it.
We also got to_string() without writing it. The standard library implements another trait, ToString, for every type that implements Display. One impl you write can switch on a whole set of methods you didn’t.
There’s no derive(Display). Debug output is for you, the programmer, and the compiler can make a fair guess at it. Display output is for your users, and only you know what it should look like. Most types that users see have both: Debug derived, Display written by hand.
Standard traits you’ll keep meeting
A few more standard traits are worth knowing by name:
Dropruns code when a value goes away. Part 6 used it to print a line at each drop. You implement it; you never calldropthe method yourself.FromandIntoconvert one type into another. Part 12 usedFromso that?could turn one error type into another. Writeimpl From<Celsius> for Fahrenheit, and you can callFahrenheit::from(c). The standard library then gives youlet f: Fahrenheit = c.into();as well, the same trick asToString.Iteratoris what aforloop uses. Its one required method isnext, and it has dozens of default methods built on it. Part 17 is all about it.PartialEq,Ord,Hashand friends are what==,sortandHashMapask for, as the table above showed.
The orphan rule
Vec<i32> doesn’t implement Display. So why not add it?
use std::fmt;
impl fmt::Display for Vec<i32> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} items", self.len())
}
}
fn main() {
let v = vec![1, 2, 3];
println!("{v}");
}
It prints:
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src/main.rs:3:1
|
3 | impl fmt::Display for Vec<i32> {
| ^^^^^^^^^^^^^^^^^^^^^^--------
| |
| `Vec` is not defined in the current crate
|
...
= note: define and implement a trait or new type instead
A crate is one unit of Rust code that the compiler builds: your program is one, and the standard library is another (Part 18 says more). The rule is this: you may implement a trait for a type only if your crate defines the trait, the type, or both. Display is the standard library’s. Vec is the standard library’s. Neither is yours, so the impl is refused. A trait or type from another crate is called foreign; one from your crate is local.
That still leaves you plenty of room. Here’s what each pairing looks like:
Every black line has your type or your trait at one end, or both. The red dashed line has std at both ends, so no crate but std may draw it. Not every impl std has is drawn.
Here are the four kinds of line in words:
- Your trait for your type,
SummaryforPoint: always allowed. - A foreign trait for your type,
DisplayorDebugforPoint: allowed. This is whatderiveand ourDisplayimpl did. - Your trait for a foreign type,
Summaryfori32: allowed. Your crate owns the trait. - A foreign trait for a foreign type,
DisplayforVec<i32>: refused, E0117.
Case 3 surprises people. impl Summary for i32 compiles, and then 42.summarize() works. Exercise 2 has a program that does the same for String.
Why the rule exists
Picture two crates, both used by your program. Each one writes impl Display for Vec<i32>, and each prints the vector differently. Now your program calls println!("{v}"). Which impl should run? There’s no good answer. Rust avoids the question: for any one trait and type, the whole program may have at most one impl. The orphan rule makes that checkable crate by crate. If an impl needs your trait or your type, no other crate can write the same one, because no other crate has your trait or your type.
The rule also means a new Rust release can add an impl for its own types without clashing with one in your code.
The newtype workaround
When you need a foreign trait on a foreign type, wrap the type in a struct of your own. Part 10 called a one-field tuple struct a newtype. The newtype is local, so the impl is allowed:
use std::fmt;
struct Scores(Vec<i32>);
impl fmt::Display for Scores {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut total = 0;
for s in &self.0 {
total += s;
}
write!(f, "{} scores, total {total}", self.0.len())
}
}
fn main() {
let scores = Scores(vec![7, 10, 4]);
println!("{scores}");
println!("first score: {}", scores.0[0]);
}
It prints:
3 scores, total 21
first score: 7
Scores costs nothing at run time. It’s exactly the size of the Vec inside it. The price is in the code: Scores doesn’t have Vec‘s methods, so you reach the vector through .0. Part 22 shows Deref, which can make a wrapper act more like the type inside.
Explain it like I’m ten
A trait is like a badge at a swimming club, say “can swim 50 metres”. The badge comes with a test. Anyone who passes the test can wear the badge. When the lifeguard asks “who can swim 50 metres?”, every kid with the badge may jump in. The lifeguard doesn’t care who the kid is, only that they have the badge.
Who may sew a badge onto a jacket? The club that made the badge may sew it onto anyone’s jacket. A parent may sew any badge onto their own kid’s jacket, once the kid passes the test. But a stranger may not sew the club’s badge onto another family’s kid. If strangers could, two of them might sew on two different versions of the same badge, and nobody would know which one counts.
The precise version
A trait is a named set of method signatures, some with default bodies. An impl provides the methods for one type, and the compiler checks that every required method is there. A trait bound such as &impl Summary lets a function accept any type with that impl, and the compiler checks every call before the program runs.
For a trait T and a type X, impl T for X is allowed when T is local or X is local. The full rule in the Rust Reference is a little wider: a foreign trait with type parameters, such as From<Point>, may be implemented for a foreign type if a local type appears in the parameters. So impl From<Point> for Vec<i32> compiles, but impl Display for Vec<Point> doesn’t, because Display has no parameter and Vec is not local even when it holds your type.
Where the analogy breaks: a badge is checked when the lifeguard looks. Rust checks every impl and every bound while it compiles, so a missing badge is a build error, not a surprise at the pool. And the orphan rule isn’t about trust. It’s about making sure the whole program, across every crate, has at most one impl for each trait and type.
Worked example: a set of visited cells
You’re writing a small grid game and want to remember which cells the player has visited. A HashSet of positions sounds right:
use std::collections::HashSet;
#[derive(Debug, PartialEq)]
struct Cell {
row: i32,
col: i32,
}
fn main() {
let mut visited = HashSet::new();
visited.insert(Cell { row: 0, col: 0 });
println!("{}", visited.len());
}
It prints:
error[E0277]: the trait bound `Cell: Eq` is not satisfied
...
11 | visited.insert(Cell { row: 0, col: 0 });
| ^^^^^^ the trait `Eq` is not implemented for `Cell`
...
help: consider annotating `Cell` with `#[derive(Eq)]`
...
error[E0277]: the trait bound `Cell: Hash` is not satisfied
...
help: consider annotating `Cell` with `#[derive(Hash)]`
Read it top down. The two errors point at the same insert call. The first part of each names the trait that’s missing: Eq, then Hash. If you read the full output, a note: shows the line in the standard library that asks for them, T: Eq + Hash. A hash set has to hash an item to find its bucket, and compare items to spot a duplicate. The help: lines name the fix. Both traits can be derived, because both fields are i32:
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Cell {
row: i32,
col: i32,
}
fn main() {
let path = [
Cell { row: 0, col: 0 },
Cell { row: 0, col: 1 },
Cell { row: 1, col: 1 },
Cell { row: 0, col: 1 },
];
let mut visited = HashSet::new();
for cell in path {
if !visited.insert(cell) {
println!("been here before: {cell:?}");
}
}
println!("{} steps, {} different cells", path.len(), visited.len());
}
It prints:
been here before: Cell { row: 0, col: 1 }
4 steps, 3 different cells
insert returns false when the item was already in the set, which gives us the “been here before” check for free. We added Clone and Copy as well, so that cell can go into the set and still be printed afterwards.
Worked example: sorting tasks with a derived Ord
A to-do list should show the most urgent tasks first, and tasks of the same urgency by name, A to Z. We can get that from derive alone, if we pick the order of fields and variants with care. Enums (Part 11) derive Ord too, and their variants compare in the order you write them, the first one smallest.
The first idea most people have is enum Priority { Low, Medium, High }, then sort and reverse. That puts High first, but reverse also flips the tie-break, so two High tasks come out Z to A. Instead, write the variants in the order the list should show them:
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Priority {
High,
Medium,
Low,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Task {
priority: Priority,
name: String,
}
fn task(priority: Priority, name: &str) -> Task {
Task {
priority,
name: name.to_string(),
}
}
fn main() {
let mut tasks = vec![
task(Priority::Low, "water plants"),
task(Priority::High, "fix login bug"),
task(Priority::Medium, "answer email"),
task(Priority::High, "back up database"),
];
tasks.sort();
for t in &tasks {
println!("{:?}: {}", t.priority, t.name);
}
}
It prints:
High: back up database
High: fix login bug
Medium: answer email
Low: water plants
High is the smallest variant, so it sorts first. The two High tasks tie on priority, so the derived Ord compares name, and “back up” comes before “fix”. The lesson: a derived order is the declaration order, fields top to bottom and variants top to bottom. If someone later moves name above priority, the list silently sorts by name. When the order matters that much, leave a comment on the struct, or write Ord by hand. Once we have closures (Part 16), sort_by_key lets you sort by whatever you pick without changing the type.
Tips and traps
- E0277 “doesn’t implement
std::fmt::Display“. You used{}on your own type. Use{:?}with#[derive(Debug)]while you work, and writeimpl fmt::Displayfor output users see. - Adding derives until the error goes away. Each derive is a promise about your type. Deriving
Copyon a type that may later get aStringfield means removing it again and fixing every place that relied on it. Derive what you use:Debugalmost always, the rest when a==, a sort or a map asks for it. - Width ignored by your
Display. Withwrite!,format!("[{p:>10}]")prints[(3, -1)], with no padding.write!ignores the width you asked for. If padding matters, build the text first and end withf.pad(&text), which applies it. - E0117 on a foreign trait and a foreign type. You can’t fix it by moving the impl to another file. Wrap the type in a newtype, or define your own trait.
- E0046 “not all trait items implemented”. The message lists the missing method by name. Copy its signature from the trait, not from memory, so the types match.
A trait is a promise a type makes, and the orphan rule makes sure only one crate can make it.
Exercises
Exercise 1. Implement Display for this type so that Money { cents: 1205 } prints as $12.05 and Money { cents: 7 } prints as $0.07. Hint: {:02} pads a number to two digits with a leading zero.
struct Money {
cents: u64,
}
fn main() {
let m = Money { cents: 1205 };
println!("{}", m.cents);
}
Exercise 2. Which of these four impls does the orphan rule allow in your own crate? Summary is your trait, and Point is your struct.
- (a)
impl Summary for String - (b)
impl std::fmt::Display for Option<i32> - (c)
impl std::fmt::Debug for Point - (d)
impl std::fmt::Display for Vec<Point>
Exercise 3. This struct won’t compile. Explain the error, then fix it two ways: once by changing the derive, once by changing the field, so that Eq stays.
#[derive(Debug, PartialEq, Eq)]
struct Parcel {
label: String,
kilos: f32,
}
fn main() {
let a = Parcel {
label: String::from("books"),
kilos: 2.5,
};
println!("{a:?}");
}
It prints:
error[E0277]: the trait bound `f32: Eq` is not satisfied
Answers
1. Divide by 100 for the dollars, and take the remainder for the cents. {:02} keeps the leading zero in $0.07.
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() {
println!("{}", Money { cents: 1205 });
println!("{}", Money { cents: 7 });
}
It prints:
$12.05
$0.07
2. (a) and (c) are allowed. (a) is your trait, and (c) is your type. (b) and (d) are refused with E0117. In (b), both Display and Option belong to the standard library. In (d), Vec still belongs to the standard library, even when it holds your Point. Here are (a) and (c) compiling:
use std::fmt;
trait Summary {
fn summarize(&self) -> String;
}
struct Point {
x: i32,
y: i32,
}
impl Summary for String {
fn summarize(&self) -> String {
format!("{} bytes of text", self.len())
}
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "P[{} {}]", self.x, self.y)
}
}
fn main() {
println!("{}", String::from("hello").summarize());
println!("{:?}", Point { x: 1, y: 2 });
}
It prints:
5 bytes of text
P[1 2]
3. Eq promises that every value equals itself. f32 can’t promise that, because NaN isn’t equal to itself, so f32 isn’t Eq, and neither is a struct that holds one. The first fix keeps the float and changes the derive to #[derive(Debug, PartialEq)]. The second keeps Eq and stores grams in a u32, which is Eq:
#[derive(Debug, PartialEq, Eq)]
struct Parcel {
label: String,
grams: u32,
}
fn main() {
let a = Parcel {
label: String::from("books"),
grams: 2500,
};
let b = Parcel {
label: String::from("books"),
grams: 2500,
};
println!("{a:?}");
println!("a == b: {}", a == b);
}
It prints:
Parcel { label: "books", grams: 2500 }
a == b: true
Use the first fix when you only need ==. Use the second when you need the type as a HashMap key or want to sort it, since those ask for Eq, Hash or Ord.
What’s next
&impl Summary was our first taste of code that works for many types at once. In Part 15, we’ll write generic functions and structs with T, add trait bounds with where, and see how the compiler turns one generic function into a separate copy for each type you use.