Rust Intermediate for Confirmed Developers: Traits and Lifetimes
Intermediate Rust for confirmed developers: traits and generics, lifetimes, closures and iterators, smart pointers, error design, modules, testing and threads, with quizzes.
Study this lesson with its quizzes on Brainbotox →
Rust traits and generics: static and dynamic dispatch
A trait defines behaviour that types can share, similar to an interface, and generics with trait bounds let one function work for every type that has that behaviour.
Defining and implementing a trait
trait Summary {
fn title(&self) -> String;
fn summarize(&self) -> String { // default method
format!("Read more: {}", self.title())
}
}
struct Article { name: String }
impl Summary for Article {
fn title(&self) -> String { self.name.clone() }
}Generics and trait bounds
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut max = items[0];
for &it in items { if it > max { max = it; } }
max
}
fn notify(item: &impl Summary) { println!("{}", item.summarize()); }
fn show<T>(x: T) where T: std::fmt::Display + Clone { }Static versus dynamic dispatch
Generics (T: Trait, impl Trait) | Trait objects (dyn Trait) | |
|---|---|---|
| Resolved | At compile time | At run time through a vtable |
| Mechanism | Monomorphization: one copy of the code per concrete type | One copy of the code, indirect calls |
| Cost | Larger binary, slower compile, fastest calls | Small indirection, no inlining |
| Mixed types in one collection | No | Yes: Vec<Box<dyn Summary>> |
Deriving common traits
#[derive(Debug, Clone, PartialEq)]
struct Point { x: i32, y: i32 }Check yourself
- What is a trait in Rust?
- What is monomorphization?
- How does dyn Trait dispatch method calls?
- Which type lets a Vec hold different types that implement Summary?
- What does the orphan rule require?
- A trait can provide a default implementation of a method.
Rust lifetimes: annotations, elision and 'static
A lifetime is the region of code during which a reference is valid, and lifetime annotations tell the compiler how the lifetimes of several references relate to each other. They never change how long a value lives.
Why annotations are needed
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}The signature says: the returned reference is valid for as long as both inputs are valid. Without 'a, the compiler cannot know which input the result borrows from.
let result;
{
let b = String::from("short");
result = longest("a long string", &b);
} // b is dropped here
// println!("{result}"); // error: b does not live long enoughLifetime elision
You rarely write lifetimes because the compiler applies three rules:
- Each reference parameter gets its own lifetime.
- If there is exactly one input lifetime, it is given to all output references.
- If one parameter is
&selfor&mut self, its lifetime is given to all output references.
That is why fn first_word(s: &str) -> &str needs no annotation.
Structs that hold references
struct Parser<'a> {
input: &'a str,
}A Parser cannot outlive the string it borrows.
String, Vec) instead of references.'static
'static means the reference can live for the whole program. String literals are &'static str. As a bound, T: 'static means the type holds no borrowed data that could expire, which is what thread spawning requires.
'static just to silence an error. It usually signals that the data should be owned or shared with Arc.Check yourself
- What does a lifetime annotation such as 'a do?
- Why does fn first_word(s: &str) -> &str compile without annotations?
- What is the lifetime of a string literal?
- What must a struct that stores a reference declare?
- In fn longest<'a>(x: &'a str, y: &'a str) -> &'a str, how long is the result valid?
- Adding lifetime annotations can make a value live longer.
Rust closures and iterators
A closure is an anonymous function that can capture variables from its environment, and an iterator is a lazy sequence of values that you transform with chained adaptors.
Closures
let factor = 3;
let triple = |x: i32| x * factor; // borrows factor
println!("{}", triple(5)); // 15
let name = String::from("Ada");
let greet = move || println!("Hi {name}"); // move: takes ownership| Trait | The closure | Can be called |
|---|---|---|
Fn | Only reads what it captured | Many times |
FnMut | Modifies what it captured | Many times |
FnOnce | Consumes what it captured | Once |
The Iterator trait
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Adaptors and consumers
let total: i32 = (1..=10)
.filter(|n| n % 2 == 0)
.map(|n| n * n)
.sum(); // 220
let names: Vec<String> = users.iter().map(|u| u.name.clone()).collect();map and filter are lazy: nothing happens until a consumer such as collect, sum, count or a for loop pulls values.Three ways to iterate a collection
| Method | Yields | The collection afterwards |
|---|---|---|
iter() | &T | Still usable |
iter_mut() | &mut T | Still usable, modified |
into_iter() | T | Consumed (moved) |
Check yourself
- What does the move keyword do on a closure?
- Which trait describes a closure that can be called only once?
- When does .map(|x| x * 2) on an iterator execute?
- What does into_iter() on a Vec<T> yield?
- What does next() return when an iterator is exhausted?
- Iterator chains in Rust are generally slower than hand-written loops.
Rust smart pointers: Box, Rc, Arc and RefCell
Smart pointers are types that own heap data and add a capability: Box for single ownership on the heap, Rc and Arc for shared ownership, and RefCell for mutation checked at run time.
| Type | Ownership | Thread-safe | Use for |
|---|---|---|---|
Box<T> | Single | If T is | Heap allocation, recursive types, trait objects |
Rc<T> | Shared, reference counted | No | Several owners in one thread |
Arc<T> | Shared, atomic counter | Yes | Several owners across threads |
RefCell<T> | Single | No | Interior mutability |
Box
enum List {
Cons(i32, Box<List>), // Box gives the recursive type a known size
Nil,
}Rc: shared ownership
use std::rc::Rc;
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a); // increments the count, no deep copy
println!("{}", Rc::strong_count(&a)); // 2The value is dropped when the last Rc is dropped. Rc gives only shared (read-only) access.
RefCell: interior mutability
use std::cell::RefCell;
let data = Rc::new(RefCell::new(vec![1, 2]));
data.borrow_mut().push(3);
println!("{:?}", data.borrow());RefCell enforces the borrowing rules at run time. Calling borrow_mut() while another borrow is active panics.Reference cycles and Weak
Two Rc values that point to each other never reach a count of zero: a memory leak. Use Weak<T> (from Rc::downgrade) for back references such as child to parent. A Weak does not keep the value alive, and upgrade() returns an Option.
Deref and Drop
Deref lets a smart pointer be used like a reference (*b, automatic method calls). Drop runs clean-up code when the value goes out of scope.
Check yourself
- Which smart pointer gives shared ownership across threads?
- What does Rc::clone(&a) do?
- What happens if you call borrow_mut() on a RefCell that is already borrowed?
- Why is Box needed in a recursive enum?
- How do you avoid a memory leak from an Rc reference cycle?
- Rc<T> can be sent safely to another thread.
Rust error design, modules and testing
Real Rust projects define their own error types, split code into modules with explicit visibility, and keep unit tests next to the code they check.
Custom error types
#[derive(Debug)]
enum ConfigError {
Io(std::io::Error),
Parse(std::num::ParseIntError),
}
impl From<std::io::Error> for ConfigError {
fn from(e: std::io::Error) -> Self { ConfigError::Io(e) }
}
fn load() -> Result<u32, ConfigError> {
let text = std::fs::read_to_string("port.txt")?; // io::Error converted by From
text.trim().parse().map_err(ConfigError::Parse)
}? operator calls From::from on the error, so it converts automatically into your function's error type when a From implementation exists.| Approach | Use in |
|---|---|
Enum error type (often with the thiserror crate) | Libraries: callers can match on variants |
anyhow::Result with .context("...") | Applications: easy propagation with context |
Box<dyn std::error::Error> | Quick programs and examples |
Modules and visibility
mod network {
pub fn connect() { helper(); }
fn helper() { } // private to the module
pub mod tls { pub fn handshake() { } }
}
use network::tls::handshake;
use crate::network::connect;Everything is private by default. pub exposes an item, and pub(crate) exposes it inside the crate only. A module can live in its own file: mod network; loads network.rs.
Testing
pub fn add(a: i32, b: i32) -> i32 { a + b }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds() { assert_eq!(add(2, 3), 5); }
#[test]
#[should_panic]
fn divides_by_zero() { let _ = 1 / std::hint::black_box(0); }
}- Unit tests sit in the same file under
#[cfg(test)]and can test private functions. - Integration tests live in the
tests/directory and use only the public API. - Code examples in documentation comments are compiled and run as doc tests.
Check yourself
- How does ? convert an io::Error into your own error type?
- Which error approach suits a library whose callers must match on failure kinds?
- What is the default visibility of items in a Rust module?
- Where do integration tests live in a Cargo project?
- What does #[cfg(test)] do?
- What does pub(crate) mean?
Rust concurrency: threads, Send, Sync, Mutex and channels
Rust's ownership rules extend to threads: the compiler refuses code that could cause a data race. This is often called fearless concurrency.
Spawning threads
use std::thread;
let data = vec![1, 2, 3];
let handle = thread::spawn(move || { // move: the thread owns data
data.iter().sum::<i32>()
});
let total = handle.join().unwrap(); // wait and get the resultSend and Sync
| Marker trait | Meaning | Not implemented by |
|---|---|---|
Send | Ownership of the value can move to another thread | Rc<T> |
Sync | The value can be referenced from several threads at once | RefCell<T>, Cell<T> |
The compiler derives these traits automatically and checks them whenever data crosses a thread boundary.
Shared state: Arc and Mutex
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..8 {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut n = c.lock().unwrap(); // guard
*n += 1;
})); // guard dropped: unlocked
}
for h in handles { h.join().unwrap(); }Message passing
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || { tx.send(42).unwrap(); });
println!("{}", rx.recv().unwrap());mpsc means multiple producer, single consumer: clone tx for more senders.
Check yourself
- Why is move usually needed in thread::spawn(move || ...)?
- What does the Send trait mean?
- What is the usual type for a counter shared and mutated by several threads?
- When is a Rust Mutex unlocked?
- What does mpsc stand for?
- The Rust compiler prevents all deadlocks.