Brainbotox · Lessons · Exams

Rust Intermediate for Confirmed Developers: Traits and Lifetimes

by lazizanie · Programming · Rust · English

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)
ResolvedAt compile timeAt run time through a vtable
MechanismMonomorphization: one copy of the code per concrete typeOne copy of the code, indirect calls
CostLarger binary, slower compile, fastest callsSmall indirection, no inlining
Mixed types in one collectionNoYes: Vec<Box<dyn Summary>>

Deriving common traits

#[derive(Debug, Clone, PartialEq)]
struct Point { x: i32, y: i32 }
Orphan rule: you can implement a trait for a type only if the trait or the type is defined in your crate. It keeps implementations coherent across crates.

Check yourself

  1. What is a trait in Rust?
  2. What is monomorphization?
  3. How does dyn Trait dispatch method calls?
  4. Which type lets a Vec hold different types that implement Summary?
  5. What does the orphan rule require?
  6. A trait can provide a default implementation of a method.

Take the quiz on Brainbotox

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 enough

Lifetime elision

You rarely write lifetimes because the compiler applies three rules:

  1. Each reference parameter gets its own lifetime.
  2. If there is exactly one input lifetime, it is given to all output references.
  3. If one parameter is &self or &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.

If lifetimes in a struct become painful, store owned data (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.

Do not add 'static just to silence an error. It usually signals that the data should be owned or shared with Arc.

Check yourself

  1. What does a lifetime annotation such as 'a do?
  2. Why does fn first_word(s: &str) -> &str compile without annotations?
  3. What is the lifetime of a string literal?
  4. What must a struct that stores a reference declare?
  5. In fn longest<'a>(x: &'a str, y: &'a str) -> &'a str, how long is the result valid?
  6. Adding lifetime annotations can make a value live longer.

Take the quiz on Brainbotox

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
TraitThe closureCan be called
FnOnly reads what it capturedMany times
FnMutModifies what it capturedMany times
FnOnceConsumes what it capturedOnce

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();
Adaptors such as 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

MethodYieldsThe collection afterwards
iter()&TStill usable
iter_mut()&mut TStill usable, modified
into_iter()TConsumed (moved)
Iterator chains compile to the same machine code as hand-written loops, and often remove bounds checks. They are a zero-cost abstraction.

Check yourself

  1. What does the move keyword do on a closure?
  2. Which trait describes a closure that can be called only once?
  3. When does .map(|x| x * 2) on an iterator execute?
  4. What does into_iter() on a Vec<T> yield?
  5. What does next() return when an iterator is exhausted?
  6. Iterator chains in Rust are generally slower than hand-written loops.

Take the quiz on Brainbotox

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.

TypeOwnershipThread-safeUse for
Box<T>SingleIf T isHeap allocation, recursive types, trait objects
Rc<T>Shared, reference countedNoSeveral owners in one thread
Arc<T>Shared, atomic counterYesSeveral owners across threads
RefCell<T>SingleNoInterior 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));   // 2

The 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

  1. Which smart pointer gives shared ownership across threads?
  2. What does Rc::clone(&a) do?
  3. What happens if you call borrow_mut() on a RefCell that is already borrowed?
  4. Why is Box needed in a recursive enum?
  5. How do you avoid a memory leak from an Rc reference cycle?
  6. Rc<T> can be sent safely to another thread.

Take the quiz on Brainbotox

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)
}
The ? operator calls From::from on the error, so it converts automatically into your function's error type when a From implementation exists.
ApproachUse 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

  1. How does ? convert an io::Error into your own error type?
  2. Which error approach suits a library whose callers must match on failure kinds?
  3. What is the default visibility of items in a Rust module?
  4. Where do integration tests live in a Cargo project?
  5. What does #[cfg(test)] do?
  6. What does pub(crate) mean?

Take the quiz on Brainbotox

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 result

Send and Sync

Marker traitMeaningNot implemented by
SendOwnership of the value can move to another threadRc<T>
SyncThe value can be referenced from several threads at onceRefCell<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(); }
In Rust the mutex owns the data it protects. You cannot reach the data without locking, and the lock is released automatically when the guard goes out of scope.

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.

The compiler prevents data races, not every concurrency bug. Deadlocks (two threads waiting for each other's lock) and logic races are still possible.

Check yourself

  1. Why is move usually needed in thread::spawn(move || ...)?
  2. What does the Send trait mean?
  3. What is the usual type for a counter shared and mutated by several threads?
  4. When is a Rust Mutex unlocked?
  5. What does mpsc stand for?
  6. The Rust compiler prevents all deadlocks.

Take the quiz on Brainbotox