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
longestneeds one butfn first(s: &str) -> &strdoes 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:
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 strb: ❌ ambiguous — two inputs, noselfc: ❌ same problem: two input lifetimes (even though one is&i32)d: ✅ rule 3 → output tied to&selfe: ✅ rule 2 applies to all outputs → both tied tox
🟢 Exercise 13.2 — Fix the dangle
Make this compile in two ways:
fn make_greeting(name: &str) -> &str {
let greeting = format!("Hello, {name}!");
&greeting
}Solution
// 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:
longest(x, y) -> &strwith both inputs sharing'alongest_with_default<'a>(x: &'a str, y: &'a str, default: &'a str) -> &'a strthat returnsdefaultif both are empty- Explain why
fn longest<'a>(x: &'a str, y: &str) -> &'a str { y }fails
Solution
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
#[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
enum Token<'a> { Word(&'a str), Number(f64), Symbol(char) }Tokenize "let x = 42 + y" into words, numbers, and symbols, skipping whitespace.
Solution
#[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
- Do lifetime annotations change how long a value lives?
- State the three elision rules.
- What does
T: 'staticmean, and what does it not mean? - Why do methods rarely need lifetime annotations?
- What's the usual right fix when you get E0515 (returning a reference to a local)?
Answers
- No — they only describe relationships the compiler then verifies.
- (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. - 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.
- Elision rule 3 assigns
&self's lifetime to the output. - Return an owned value instead of a reference.
