Skip to content
RustLearn

Module 13 Exercises — Lifetimes

How to use this page

Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.

Before you start, be able to say:

  • what a lifetime annotation does and does not change;
  • why longest needs one but fn first(s: &str) -> &str does not;
  • the three elision rules, in order.

When a drill produces E0106, try the "just own it" fix first (return String) and confirm it compiles — then go back and do it properly with a reference. Seeing both makes the trade-off concrete instead of theoretical.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 13.1 — Apply elision by hand

For each signature, state whether it compiles without annotations, and if so what the elided lifetimes are:

rust
fn a(s: &str) -> &str;
fn b(x: &str, y: &str) -> &str;
fn c(x: &str, y: &i32) -> &str;
fn d(&self, x: &str) -> &str;
fn e(x: &str) -> (&str, &str);
Answers
  • a: ✅ rule 2 → fn a<'a>(s: &'a str) -> &'a str
  • b: ❌ ambiguous — two inputs, no self
  • c: ❌ same problem: two input lifetimes (even though one is &i32)
  • d: ✅ rule 3 → output tied to &self
  • e: ✅ rule 2 applies to all outputs → both tied to x

🟢 Exercise 13.2 — Fix the dangle

Make this compile in two ways:

rust
fn make_greeting(name: &str) -> &str {
    let greeting = format!("Hello, {name}!");
    &greeting
}
Solution
rust
// 1. return an owned String
fn make_greeting(name: &str) -> String {
    format!("Hello, {name}!")
}

// 2. write into a caller-provided buffer
fn make_greeting_into<'a>(name: &str, buf: &'a mut String) -> &'a str {
    buf.clear();
    buf.push_str("Hello, ");
    buf.push_str(name);
    buf.push('!');
    buf
}

Option 1 is what you should almost always do.

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 13.3 — longest variants

Implement:

  1. longest(x, y) -> &str with both inputs sharing 'a
  2. longest_with_default<'a>(x: &'a str, y: &'a str, default: &'a str) -> &'a str that returns default if both are empty
  3. Explain why fn longest<'a>(x: &'a str, y: &str) -> &'a str { y } fails
Solution
rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

fn longest_with_default<'a>(x: &'a str, y: &'a str, default: &'a str) -> &'a str {
    if x.is_empty() && y.is_empty() { default } else { longest(x, y) }
}

(3) fails because y has an anonymous, unrelated lifetime 'b that the compiler cannot prove outlives 'a. Error: lifetime may not live long enough.

🟡 Exercise 13.4 — Zero-copy CSV field extractor

Write struct Row<'a> { fields: Vec<&'a str> } with fn parse(line: &'a str) -> Row<'a> and fn get(&self, i: usize) -> Option<&'a str>. Verify that no allocation of string data occurs (only the Vec of pointers).

Solution
rust
#[derive(Debug)]
struct Row<'a> { fields: Vec<&'a str> }

impl<'a> Row<'a> {
    fn parse(line: &'a str) -> Row<'a> {
        Row { fields: line.split(',').map(str::trim).collect() }
    }
    fn get(&self, i: usize) -> Option<&'a str> {
        self.fields.get(i).copied()
    }
}

fn main() {
    let data = String::from("id, name, email");
    let row = Row::parse(&data);
    println!("{:?}", row.get(1));       // Some("name")
    // drop(data);                      // ❌ would not compile: row borrows it
    println!("{row:?}");
}

Note get returns Option<&'a str>, not Option<&str> — the field outlives the Row itself, which is what makes this genuinely zero-copy for downstream callers.

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 13.5 — Tokenizer with lifetimes

Build a struct Tokenizer<'a> { input: &'a str, pos: usize } implementing Iterator with type Item = Token<'a> where

rust
enum Token<'a> { Word(&'a str), Number(f64), Symbol(char) }

Tokenize "let x = 42 + y" into words, numbers, and symbols, skipping whitespace.

Solution
rust
#[derive(Debug, PartialEq)]
enum Token<'a> { Word(&'a str), Number(f64), Symbol(char) }

struct Tokenizer<'a> { input: &'a str, pos: usize }

impl<'a> Tokenizer<'a> {
    fn new(input: &'a str) -> Self { Tokenizer { input, pos: 0 } }

    fn rest(&self) -> &'a str { &self.input[self.pos..] }
}

impl<'a> Iterator for Tokenizer<'a> {
    type Item = Token<'a>;

    fn next(&mut self) -> Option<Token<'a>> {
        // skip whitespace
        let skipped = self.rest().len() - self.rest().trim_start().len();
        self.pos += skipped;

        let rest = self.rest();
        let first = rest.chars().next()?;

        if first.is_alphabetic() || first == '_' {
            let end = rest.find(|c: char| !c.is_alphanumeric() && c != '_')
                          .unwrap_or(rest.len());
            self.pos += end;
            Some(Token::Word(&rest[..end]))
        } else if first.is_ascii_digit() {
            let end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')
                          .unwrap_or(rest.len());
            self.pos += end;
            Some(Token::Number(rest[..end].parse().ok()?))
        } else {
            self.pos += first.len_utf8();
            Some(Token::Symbol(first))
        }
    }
}

fn main() {
    let src = String::from("let x = 42 + y");
    let tokens: Vec<Token> = Tokenizer::new(&src).collect();
    println!("{tokens:?}");
    assert_eq!(tokens[0], Token::Word("let"));
    assert_eq!(tokens[3], Token::Number(42.0));
    assert_eq!(tokens[4], Token::Symbol('+'));
}

Every Token::Word is a slice into the original string — no allocation. This is exactly how real parsers in Rust (like syn or serde_json's borrowed mode) work, and it's the single best motivation for learning lifetimes properly.

Self-check

  1. Do lifetime annotations change how long a value lives?
  2. State the three elision rules.
  3. What does T: 'static mean, and what does it not mean?
  4. Why do methods rarely need lifetime annotations?
  5. What's the usual right fix when you get E0515 (returning a reference to a local)?
Answers
  1. No — they only describe relationships the compiler then verifies.
  2. (a) each elided input gets its own lifetime; (b) one input lifetime is assigned to all outputs; (c) &self's lifetime is assigned to all outputs.
  3. It means the type contains no references shorter than the whole program (all owned types qualify). It does not mean the value must live forever.
  4. Elision rule 3 assigns &self's lifetime to the output.
  5. Return an owned value instead of a reference.

Next: Module 14 — Closures & Iterators