Make + work on your own types, see why Iterator has an associated type and not a parameter, follow a Box through Deref to a str, and learn exactly when Rust runs Drop.
Part 14 showed how to write a trait and implement it. This part covers the trait features you meet next: associated types, operators like + and [], Deref, the full story of Drop, supertraits, and what to write when two traits have a method with the same name.
It builds on Part 15 (generics), Part 17 (your own iterator) and Part 20 (Box and Rc). Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
Here’s a small type for a point or a direction on a flat plane. Does the last line of main compile?
#[derive(Debug, Clone, Copy)]
struct Vec2 {
x: f64,
y: f64,
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
let c = a + b;
println!("{c:?}");
}
It doesn’t:
error[E0369]: cannot add `Vec2` to `Vec2`
--> src/main.rs:10:15
|
10 | let c = a + b;
| - ^ - Vec2
| |
| Vec2
|
note: an implementation of `Add` might be missing for `Vec2`
Rust doesn’t know what adding two Vec2s means, and it won’t guess. The note names the fix: + is the trait Add. In Rust, every operator is a trait, and implementing that trait teaches your type the operator. Before we do that, we need one idea that Add uses: the associated type.
Associated types: one item type per impl
Part 17 showed the Iterator trait, stripped down:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
type Item is an associated type: a type that each impl must name. Why not write the trait with a generic parameter instead, as Iterator<T>? We can try it. Here’s a trait shaped that way, under a different name so it doesn’t clash with the real one:
trait Source<T> {
fn next_item(&mut self) -> Option<T>;
}
struct Numbers {
n: u32,
}
impl Source<u32> for Numbers {
fn next_item(&mut self) -> Option<u32> {
self.n += 1;
Some(self.n)
}
}
impl Source<String> for Numbers {
fn next_item(&mut self) -> Option<String> {
self.n += 1;
Some(format!("#{}", self.n))
}
}
fn main() {
let mut nums = Numbers { n: 0 };
let first = nums.next_item();
println!("{first:?}");
}
It prints:
error[E0283]: type annotations needed for `Option<_>`
--> src/main.rs:25:9
|
25 | let first = nums.next_item();
| ^^^^^ --------- type must be known at this point
|
note: multiple `impl`s satisfying `Numbers: Source<_>` found
With a parameter, Source<u32> and Source<String> are two different traits, so one type may implement both. Then every call to next_item is a question: which one did you mean? You’d have to write the type at every call, and for loops, map and sum would all need it too.
An associated type rules that out. A type can implement Iterator only once, so it has exactly one Item. A second impl Iterator for Numbers with type Item = String is refused with E0119, “conflicting implementations of trait Iterator“.
So here’s the rule for your own traits:
- Use an associated type when each type has one natural answer. An iterator yields one kind of item. A container holds one kind of thing.
- Use a generic parameter when one type can sensibly implement the trait many times, once per parameter. We’ll see
Mul<f64>andMul<Vec2>on the same type below.
Your own iterator, with type Item
Here’s an iterator of Fibonacci numbers. The impl names type Item = u64, and from then on Self::Item and u64 mean the same thing:
struct Fib {
current: Option<u64>,
next: Option<u64>,
}
impl Fib {
fn new() -> Fib {
Fib {
current: Some(0),
next: Some(1),
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let value = self.current?;
self.current = self.next;
self.next = self.next.and_then(|n| value.checked_add(n));
Some(value)
}
}
fn total(items: impl Iterator<Item = u64>) -> u64 {
items.sum()
}
fn main() {
let first: Vec<u64> = Fib::new().take(10).collect();
println!("{first:?}");
println!("sum of the first 10: {}", total(Fib::new().take(10)));
println!("how many fit in a u64: {}", Fib::new().count());
}
It prints:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
sum of the first 10: 88
how many fit in a u64: 94
Two things to notice. First, the iterator ends by itself. checked_add returns None when the sum would overflow a u64 (Part 2), so next becomes None one step after the last number that fits. On the call after that, self.current? (the ? from Part 12) returns None from next. That’s why count can finish instead of panicking on overflow.
Then look at total. Its bound is impl Iterator<Item = u64>: “any iterator whose Item is u64“. That Item = u64 is how you put a condition on an associated type. You can’t write Iterator<u64>, because Iterator has no parameter.
Default type parameters: Add<Rhs = Self>
Now we can read the real Add trait. Simplified from the standard library, it looks like this:
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
It has both kinds of type:
Rhsis a generic parameter: the type on the right-hand side of+.= Selfis a default type parameter. If you writeimpl Add for Vec2and say nothing aboutRhs, it meansimpl Add<Vec2> for Vec2.Outputis an associated type: whata + bgives back. For one pair of left and right types, there’s one answer.
So a + b is short for Add::add(a, b). And since Rhs is a parameter, one type can have several Add impls, one per right-hand type. The default only saves typing in the common case where both sides are the same type.
Operator overloading
The traits live in std::ops. Here’s Vec2 with five of them:
use std::ops::{Add, AddAssign, Mul, Neg, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 {
x: self.x * k,
y: self.y * k,
}
}
}
impl Mul<Vec2> for Vec2 {
type Output = f64;
fn mul(self, other: Vec2) -> f64 {
self.x * other.x + self.y * other.y
}
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2 {
x: -self.x,
y: -self.y,
}
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, other: Vec2) {
self.x += other.x;
self.y += other.y;
}
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
println!("a + b = {:?}", a + b);
println!("b - a = {:?}", b - a);
println!("a * 3 = {:?}", a * 3.0);
println!("a * b = {}", a * b);
println!("-a = {:?}", -a);
let mut pos = Vec2 { x: 0.0, y: 0.0 };
pos += a;
pos += b;
println!("pos = {pos:?}");
println!("a + b == b + a: {}", a + b == b + a);
}
It prints:
a + b = Vec2 { x: 4.0, y: 6.0 }
b - a = Vec2 { x: 2.0, y: 2.0 }
a * 3 = Vec2 { x: 3.0, y: 6.0 }
a * b = 11
-a = Vec2 { x: -1.0, y: -2.0 }
pos = Vec2 { x: 4.0, y: 6.0 }
a + b == b + a: true
Each operator maps to one method:
| You write | Rust calls | Trait |
|---|---|---|
a + b |
a.add(b) |
Add |
a - b |
a.sub(b) |
Sub |
a * b |
a.mul(b) |
Mul |
-a |
a.neg() |
Neg |
a += b |
a.add_assign(b) |
AddAssign |
a[i] |
*a.index(i) |
Index |
a == b |
a.eq(&b) |
PartialEq |
Look at the two Mul impls. a * 3.0 scales the vector and gives a Vec2. a * b is the dot product and gives an f64. That’s the generic parameter at work: two impls, one per right-hand type, each with its own Output. This is something Iterator couldn’t do, and doesn’t need to.
add, sub, mul and neg take self by value. That’s fine for Vec2, which is Copy. For a type that owns heap memory, such as a big matrix, a + b would move both, so libraries often also implement Add for &Matrix, which lets you write &a + &b.
AddAssign takes &mut self and changes the value in place. It isn’t derived from Add: if you want +=, you implement it yourself.
Index: what [] means for your type
Index gives a[i] a meaning. The index can be any type you choose. Here a grid uses a (row, column) pair, and IndexMut lets you assign through it:
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
cells: Vec<char>,
}
impl Grid {
fn new(width: usize, height: usize) -> Grid {
Grid {
width,
cells: vec!['.'; width * height],
}
}
}
impl Index<(usize, usize)> for Grid {
type Output = char;
fn index(&self, (row, col): (usize, usize)) -> &char {
assert!(col < self.width, "column {col} is outside the grid");
&self.cells[row * self.width + col]
}
}
impl IndexMut<(usize, usize)> for Grid {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut char {
assert!(col < self.width, "column {col} is outside the grid");
&mut self.cells[row * self.width + col]
}
}
fn main() {
let mut g = Grid::new(4, 2);
g[(0, 1)] = '#';
g[(1, 3)] = '@';
println!("bottom right: {}", g[(1, 3)]);
for row in g.cells.chunks(g.width) {
let line: String = row.iter().collect();
println!("{line}");
}
}
It prints:
bottom right: @
.#..
...@
index returns a reference, &char, and g[(1, 3)] means *g.index((1, 3)). That’s why [] on a Vec<String> gives you a place, not a moved value, as Part 6 found out. The assert! matters: without it, g[(0, 5)] on a 4-wide grid would quietly land in the next row.
Deref: following a pointer to what’s inside
Part 20 showed that Box and Rc act like the value they hold, thanks to the Deref trait. Here’s the trait:
trait Deref {
type Target: ?Sized;
fn deref(&self) -> &Self::Target;
}
Target is an associated type again: a Box<String> derefs to exactly one thing, a String. The ?Sized lets the target be a type with no fixed size, such as str. Part 27 explains sizes; for now, read it as “Target may be str or a slice”.
deref turns &Self into &Target. Rust calls it for you in three places: when you write *x, when you call a method that x‘s own type doesn’t have, and when you pass a reference where a different reference type is wanted. That last one is deref coercion, and it can take several steps:
use std::ops::Deref;
fn takes(s: &str) -> usize {
s.len()
}
fn main() {
let b: Box<String> = Box::new(String::from("hello"));
println!("takes(&b) = {}", takes(&b));
let step0 = &b;
let step1: &String = step0.deref();
let step2: &str = step1.deref();
println!("by hand = {}", takes(step2));
let stars = &**b;
println!("with stars = {}", takes(stars));
}
It prints:
takes(&b) = 5
by hand = 5
with stars = 5
&b is a &Box<String>, and takes wants a &str. The types don’t match, so Rust looks for a Deref impl. Box<T> derefs to T, which turns &Box<String> into &String. Still no match, so it tries again. String derefs to str, which gives &str. Now it matches. The step lines make the same two calls by hand (step0 is the &Box<String>), and &**b writes them with stars: *b is the String, **b is the str, and & borrows it.
Deref coercion follows one Deref impl per step until the type matches. Each reference on the left points one level deeper into the same memory. The grey arrows are type conversions; the black ones, as always, mean “owns”.
Here is the figure in words:
&bis a&Box<String>. It points atb, the box on the stack.Box<T>implementsDerefwithTarget = T. One step turns the&Box<String>into a&String, which points at theStringon the heap that the box owns.StringimplementsDerefwithTarget = str. A second step turns&Stringinto&str, which points at the five bytes of “hello”.&strmatches the parameter oftakes, so Rust stops. The compiler did all of this while it built the program. At run time it’s two pointer loads, and nothing is copied.
Your own Deref, and DerefMut
DerefMut is the same idea for &mut: it turns &mut Self into &mut Target. Here’s a small box of our own that implements both:
use std::ops::{Deref, DerefMut};
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for MyBox<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
fn shout(text: &str) -> String {
text.to_uppercase()
}
fn main() {
let mut name = MyBox(String::from("ana"));
name.push_str(" lima");
println!("{} has {} letters", shout(&name), name.len());
let mut count = MyBox(10);
*count += 5;
println!("count = {}", *count);
}
It prints:
ANA LIMA has 8 letters
count = 15
MyBox has no push_str or len of its own. Rust doesn’t find them on MyBox, so it derefs to String and finds them there. push_str needs &mut String, so that call uses DerefMut. shout(&name) goes &MyBox<String> to &String to &str, the same chain as the figure with our impl in the first step. *count += 5 uses DerefMut to reach the number inside.
Deref is for pointers, not for inheritance
Deref is tempting as a shortcut for inheritance from other languages. A Dog holds an Animal, derefs to it, and seems to get all of Animal‘s methods. It half works, and the half that doesn’t is the trouble:
use std::ops::Deref;
struct Animal {
name: String,
}
impl Animal {
fn describe(&self) -> String {
format!("an animal called {}", self.name)
}
}
trait Speak {
fn speak(&self) -> String;
}
impl Speak for Animal {
fn speak(&self) -> String {
format!("{} makes a sound", self.name)
}
}
struct Dog {
animal: Animal,
}
impl Deref for Dog {
type Target = Animal;
fn deref(&self) -> &Animal {
&self.animal
}
}
fn announce(x: &impl Speak) {
println!("{}", x.speak());
}
fn main() {
let rex = Dog {
animal: Animal {
name: String::from("Rex"),
},
};
println!("{}", rex.describe());
println!("{}", rex.speak());
announce(&rex);
}
It prints:
error[E0277]: the trait bound `Dog: Speak` is not satisfied
--> src/main.rs:46:14
|
46 | announce(&rex);
| -------- ^^^^ unsatisfied trait bound
| |
| required by a bound introduced by this call
|
help: the trait `Speak` is not implemented for `Dog`
...
help: the trait `Speak` is implemented for `Animal`
rex.describe() and rex.speak() compile: method calls follow Deref. But a trait bound doesn’t. announce asks “does Dog implement Speak?”, and the answer is no. Coercion only changes the type of a reference to match a concrete parameter type; it doesn’t make Dog an Animal for traits, generics or ==. So a Dog acts like an Animal in some places and not in others, and a reader has to know the Deref is there to understand any of it.
The standard library’s docs say when Deref is a good idea: when your type transparently behaves like the target, the deref is cheap and can’t fail, and nobody will be surprised by the coercion. That fits Box, Rc, String (to str) and Vec (to a slice). For Dog, write impl Speak for Dog that calls self.animal.speak(), or a method that returns &Animal. Being explicit costs a few lines and saves the confusion.
Drop in depth
Part 6 printed a line from Drop to watch values go away. Here are the rules for the order:
- Local variables are dropped in reverse order of declaration, at the end of their scope.
- A value with fields runs its own
dropfirst, while every field is still there. Then its fields are dropped, in declaration order, which is the opposite of locals. - Tuples and arrays drop their items first to last.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
struct Pair {
first: Noisy,
second: Noisy,
}
impl Drop for Pair {
fn drop(&mut self) {
println!(
"drop Pair, fields still here: {} and {}",
self.first.0, self.second.0
);
}
}
fn main() {
let _a = Noisy("local a");
let _pair = Pair {
first: Noisy("field first"),
second: Noisy("field second"),
};
let _items = [Noisy("item 0"), Noisy("item 1")];
let _b = Noisy("local b");
println!("end of main");
}
It prints:
end of main
drop local b
drop item 0
drop item 1
drop Pair, fields still here: field first and field second
drop field first
drop field second
drop local a
Read it from the top. The locals go in reverse: _b, then _items, then _pair, then _a. Inside the array, items go first to last. Pair‘s own drop runs before its fields are touched, so it can still read both fields. Then the fields go, first before second.
Vec is the odd one out: its docs say it doesn’t promise an order for its items. Don’t write code that depends on it.
You can’t call .drop() yourself
To drop a value early, you might try calling the method:
struct Connection;
impl Drop for Connection {
fn drop(&mut self) {
println!("connection closed");
}
}
fn main() {
let c = Connection;
c.drop();
}
It prints:
error[E0040]: explicit use of destructor method
--> src/main.rs:11:7
|
11 | c.drop();
| ^^^^ explicit destructor calls not allowed
|
help: consider using `drop` function
If you could call c.drop(), then c would still be in scope, and Rust would call drop again at the closing }. That’s a double free, the bug Part 6 started with. The fix the compiler names is std::mem::drop(c), which is in scope as plain drop. It’s an ordinary function with an empty body that takes ownership of its argument. Its parameter goes out of scope as it returns, and Rust drops it there, once. After the call, c is moved, so you can’t use it again.
Copy and Drop don’t mix
#[derive(Clone, Copy)]
struct Ticket(u32);
impl Drop for Ticket {
fn drop(&mut self) {
println!("ticket {} used", self.0);
}
}
fn main() {
let t = Ticket(1);
println!("{}", t.0);
}
It prints:
error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor
A Copy type is duplicated by copying its bytes, with no code run. If a Ticket were both, let u = t; would make two tickets, and each would run drop. A type that needs clean-up code is a type that owns something, and Part 6 said a type that owns something can’t be Copy.
Supertraits
Sometimes a trait only makes sense for types that have another trait. A trait for printing a value in a box of dashes needs the value’s Display text. You say so with a supertrait:
use std::fmt;
trait Pretty: fmt::Display {
fn pretty(&self) -> String {
let text = self.to_string();
let line = "-".repeat(text.len());
format!("{line}\n{text}\n{line}")
}
}
struct Score(u32);
impl fmt::Display for Score {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "score: {}", self.0)
}
}
impl Pretty for Score {}
fn main() {
println!("{}", Score(42).pretty());
}
It prints:
---------
score: 42
---------
trait Pretty: fmt::Display reads “to be Pretty, a type must also be Display“. Inside the trait, that’s why self.to_string() works: every Pretty type is known to be Display, and Display brings to_string. It’s a requirement, not inheritance: Score still writes its own Display impl. Leave that impl out, and the compiler says so at the impl Pretty line:
error[E0277]: `Score` doesn't implement `std::fmt::Display`
--> src/main.rs:11:17
|
11 | impl Pretty for Score {}
| ^^^^^ unsatisfied trait bound
Two methods with the same name
Two traits may each have a method called name, and one type may implement both. Then device.name() is ambiguous, and Rust refuses to pick (error E0034, “multiple applicable items in scope”). You name the trait instead:
trait Printer {
fn name(&self) -> String;
}
trait Scanner {
fn name(&self) -> String;
}
struct Office;
impl Office {
fn name(&self) -> String {
String::from("office machine")
}
}
impl Printer for Office {
fn name(&self) -> String {
String::from("printer P-100")
}
}
impl Scanner for Office {
fn name(&self) -> String {
String::from("scanner S-20")
}
}
fn main() {
let device = Office;
println!("{}", device.name());
println!("{}", Printer::name(&device));
println!("{}", Scanner::name(&device));
println!("{}", <Office as Scanner>::name(&device));
}
It prints:
office machine
printer P-100
scanner S-20
scanner S-20
Because Office also has an inherent method called name, device.name() picks that one: a type’s own methods win over trait methods. Printer::name(&device) calls the trait’s method, with &device passed as self. The last line is the fully qualified form, <Type as Trait>::method. It names both the type and the trait, so nothing is left to guess.
You need the full form for functions with no self, because then there’s no value to tell Rust the type:
trait Config {
fn file_name() -> String;
}
struct Server;
struct Client;
impl Config for Server {
fn file_name() -> String {
String::from("server.toml")
}
}
impl Config for Client {
fn file_name() -> String {
String::from("client.toml")
}
}
fn main() {
println!("{}", Config::file_name());
}
It prints:
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
...
help: use a fully-qualified path to one of the available implementations
|
21 | println!("{}", <Server as Config>::file_name());
| ++++++++++ +
21 | println!("{}", <Client as Config>::file_name());
Config::file_name() could be either impl. <Server as Config>::file_name() says which. Here Server::file_name() would work too, but only because Server has no inherent file_name of its own to win.
Worked example: money that can’t be mixed up with numbers
Money stored as a float gets rounding errors, so we keep whole cents in an i64. A newtype, the one-field wrapper from Part 14, stops a raw number from sneaking into a sum. First, the mistake it catches:
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Money {
cents: i64,
}
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money {
cents: self.cents + other.cents,
}
}
}
fn main() {
let price = Money { cents: 1250 };
let total = price + 500;
println!("{total:?}");
}
It prints:
error[E0308]: mismatched types
--> src/main.rs:19:25
|
19 | let total = price + 500;
| ----- ^^^ expected `Money`, found integer
| |
| expected because this is `Money`
Read it from the right. The compiler expected a Money on the right of +, because the only Add impl is Add<Money> for Money, and it found an integer. Is 500 cents or dollars? The program has no way to know, and that’s the point. The fix isn’t impl Add<i64> for Money. It’s to say what the number is.
Here’s the full type. It adds Display, AddAssign, multiplying by a quantity, and Sum, which is the trait that makes .sum() work on an iterator of Money:
use std::fmt;
use std::iter::Sum;
use std::ops::{Add, AddAssign, Mul, Neg, Sub};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Money {
cents: i64,
}
impl Money {
fn dollars(d: i64) -> Money {
Money { cents: d * 100 }
}
fn cents(c: i64) -> Money {
Money { cents: c }
}
}
impl fmt::Display for Money {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let sign = if self.cents < 0 { "-" } else { "" };
let c = self.cents.abs();
write!(f, "{sign}${}.{:02}", c / 100, c % 100)
}
}
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money::cents(self.cents + other.cents)
}
}
impl Sub for Money {
type Output = Money;
fn sub(self, other: Money) -> Money {
Money::cents(self.cents - other.cents)
}
}
impl Neg for Money {
type Output = Money;
fn neg(self) -> Money {
Money::cents(-self.cents)
}
}
impl Mul<i64> for Money {
type Output = Money;
fn mul(self, quantity: i64) -> Money {
Money::cents(self.cents * quantity)
}
}
impl AddAssign for Money {
fn add_assign(&mut self, other: Money) {
self.cents += other.cents;
}
}
impl Sum for Money {
fn sum<I: Iterator<Item = Money>>(iter: I) -> Money {
iter.fold(Money::cents(0), |acc, m| acc + m)
}
}
fn main() {
let lines = [
("notebook", Money::cents(1250), 2),
("pen", Money::cents(199), 5),
("bag", Money::dollars(30), 1),
];
let mut subtotal = Money::cents(0);
for (item, price, qty) in lines {
let line = price * qty;
println!("{item:<10} {qty} x {price} = {line}");
subtotal += line;
}
let discount = Money::dollars(5);
let total = subtotal - discount;
println!("subtotal {subtotal}, discount {}, total {total}", -discount);
let same: Money = lines.iter().map(|&(_, price, qty)| price * qty).sum();
println!("same subtotal with sum: {}", same == subtotal);
println!("over $60: {}", total > Money::dollars(60));
}
It prints:
notebook 2 x $12.50 = $25.00
pen 5 x $1.99 = $9.95
bag 1 x $30.00 = $30.00
subtotal $64.95, discount -$5.00, total $59.95
same subtotal with sum: true
over $60: false
Every place a number becomes money says so: Money::cents(1250) or Money::dollars(30). price * qty reads like the arithmetic it is, because Mul<i64> has a plain number on the right, and a quantity really is a plain number. Sum has a generic method, sum<I: Iterator<Item = Money>>, which uses the same associated-type bound we wrote for total earlier. The derived PartialOrd and Ord compare the one field, so > works too.
Real code would also guard against overflow (checked_add) and keep a currency next to the cents. The shape stays the same.
Worked example: a guard that runs code on drop
Drop is how Rust does clean-up: a file closes, a lock unlocks, a buffer is freed, all when the owner goes out of scope. You can use it for your own clean-up too. This Step guard prints when a step of work starts and ends, and it ends even if the function returns early:
struct Step {
name: &'static str,
}
impl Step {
fn start(name: &'static str) -> Step {
println!("start {name}");
Step { name }
}
}
impl Drop for Step {
fn drop(&mut self) {
println!("end {}", self.name);
}
}
fn load(ok: bool) -> Result<u32, String> {
let _step = Step::start("load");
if !ok {
return Err(String::from("file missing"));
}
println!(" reading...");
Ok(42)
}
fn main() {
let _outer = Step::start("main");
println!("{:?}", load(true));
println!("{:?}", load(false));
let _ = Step::start("oops");
println!("after oops");
}
It prints:
start main
start load
reading...
end load
Ok(42)
start load
end load
Err("file missing")
start oops
end oops
after oops
end main
The early return Err(...) still printed end load: leaving a function by any path drops its locals. That’s why Rust code rarely needs a finally block.
Now look at oops. It ended at once, before after oops. let _ = ... doesn’t bind the value to anything. _ is a pattern that matches and throws away, so the new Step is a temporary, and it’s dropped at the end of that statement. let _outer = ... is different: _outer is a real variable with a name that starts with an underscore, which only tells the compiler not to warn that it’s unused. It lives to the end of main. For a guard, always give it a name.
Tips and traps
3.0 * vdoesn’t compile whenv * 3.0does. The error is E0277, “cannot multiply{float}byVec2“. You wroteMul<f64> for Vec2, but the left side decides the impl. Addimpl Mul<Vec2> for f64too. The orphan rule allows it, becauseVec2is yours.+=missing after you wroteAdd. The error is E0368, “binary assignment operation+=cannot be applied”.AddAssignis its own trait; implement it.- A trait with a parameter where an associated type would do. If every type would implement it once, callers end up writing type annotations everywhere (E0283). Use
type Item. - Deref to fake inheritance. Methods seem to work, then a trait bound fails with E0277. Implement the trait on your type, or expose the inner value with a method.
let _ = guard;drops the guard at once. Uselet _guard = .... The underscore name keeps the value; a bare_doesn’t.- Calling
x.drop(). E0040. Calldrop(x)instead, and expectxto be moved afterwards. - E0034 “multiple applicable items in scope”. Two traits gave your type a method with the same name. Write
Trait::method(&value), or<Type as Trait>::method(...)when there’s noself.
An operator, a deref and the end of a scope are each a call to a trait method, and you can write that method for your own type.
Exercises
Exercise 1. Give Vec2 from this part a Sub impl if it doesn’t have one, then add SubAssign and impl Mul<Vec2> for f64, so that this main compiles and prints Vec2 { x: 1.0, y: 2.0 } and Vec2 { x: 2.0, y: 4.0 }:
fn main() {
let mut p = Vec2 { x: 4.0, y: 6.0 };
p -= Vec2 { x: 3.0, y: 4.0 };
println!("{p:?}");
println!("{:?}", 2.0 * p);
}
Exercise 2. Using Noisy from the Drop section, predict every line this prints, in order:
struct Team {
lead: Noisy,
members: (Noisy, Noisy),
}
fn main() {
let t = Team {
lead: Noisy("lead"),
members: (Noisy("m1"), Noisy("m2")),
};
let solo = Noisy("solo");
drop(solo);
println!("still have {}", t.lead.0);
}
Exercise 3. A SortedList keeps its numbers in order. Implement Deref with Target = [i32] so that list.len(), list.contains(&5), list[0] and for n in list.iter() all work without writing those methods. Then explain why you should not implement DerefMut.
struct SortedList {
items: Vec<i32>,
}
impl SortedList {
fn insert(&mut self, n: i32) {
let pos = self.items.partition_point(|&x| x < n);
self.items.insert(pos, n);
}
}
Answers
1. -= is SubAssign. 2.0 * p has an f64 on the left, so the impl is Mul<Vec2> for f64. That’s a foreign trait on a foreign type, allowed because Vec2 is the trait’s parameter. It reuses the Mul<f64> for Vec2 we already have.
use std::ops::{Mul, SubAssign};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 {
Vec2 {
x: self.x * k,
y: self.y * k,
}
}
}
impl Mul<Vec2> for f64 {
type Output = Vec2;
fn mul(self, v: Vec2) -> Vec2 {
v * self
}
}
impl SubAssign for Vec2 {
fn sub_assign(&mut self, other: Vec2) {
self.x -= other.x;
self.y -= other.y;
}
}
fn main() {
let mut p = Vec2 { x: 4.0, y: 6.0 };
p -= Vec2 { x: 3.0, y: 4.0 };
println!("{p:?}");
println!("{:?}", 2.0 * p);
}
It prints:
Vec2 { x: 1.0, y: 2.0 }
Vec2 { x: 2.0, y: 4.0 }
2. drop(solo) drops solo at once. Then still have lead prints. At the end of main, t is dropped. Team has no Drop impl of its own, so only its fields drop, in declaration order: lead, then the tuple members, whose items go first to last.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
struct Team {
lead: Noisy,
members: (Noisy, Noisy),
}
fn main() {
let t = Team {
lead: Noisy("lead"),
members: (Noisy("m1"), Noisy("m2")),
};
let solo = Noisy("solo");
drop(solo);
println!("still have {}", t.lead.0);
println!("{} members", [&t.members.0, &t.members.1].len());
}
We added the last line so the compiler doesn’t warn that members is never read. It doesn’t change the order.
It prints:
drop solo
still have lead
2 members
drop lead
drop m1
drop m2
3. Deref gives shared access to the slice, so every &self method of [i32] works on a SortedList.
use std::ops::Deref;
struct SortedList {
items: Vec<i32>,
}
impl SortedList {
fn new() -> SortedList {
SortedList { items: Vec::new() }
}
fn insert(&mut self, n: i32) {
let pos = self.items.partition_point(|&x| x < n);
self.items.insert(pos, n);
}
}
impl Deref for SortedList {
type Target = [i32];
fn deref(&self) -> &[i32] {
&self.items
}
}
fn main() {
let mut list = SortedList::new();
for n in [7, 2, 9, 5] {
list.insert(n);
}
println!("len {}, has 5: {}", list.len(), list.contains(&5));
println!("first {}, last {}", list[0], list[list.len() - 1]);
let doubled: Vec<i32> = list.iter().map(|n| n * 2).collect();
println!("{doubled:?}");
}
It prints:
len 4, has 5: true
first 2, last 9
[4, 10, 14, 18]
DerefMut would hand out &mut [i32], and then anyone could write list[0] = 100 or call list.reverse(), and the list would no longer be sorted. Leaving it out means the only way to change the list is insert, which keeps the order. This is a case where Deref fits: a SortedList really is a slice of numbers to read, and the deref is cheap and can’t fail.
What’s next
So far every program has run on one thread. In Part 23, we’ll start threads with spawn, move values into them, and see how the traits Send and Sync decide what may cross from one thread to another.