Last time I said I didn’t know yet what to write about. Here’s what I’ve settled on: while I work on the project, I keep notes of the moments where I got stuck and Claude got me unstuck. Reading them back, the conversations themselves are more useful than any summary I could write afterwards, because my wrong turns are in them. So this post, and probably the next few, are dialogs between me and Claude:
That’s me. My lines are as I typed them, lowercase and all.
And this is Claude, trimmed to the parts that mattered.
Everything outside the boxes is me again, commenting afterwards.
The topic is lifetimes, the thing every Rust newcomer gets warned about. I’d been away traveling and off the project for a few weeks (here and here) and was refreshing my Rust by reading Amos’s A half-hour to learn Rust. This snippet from the closures section stopped me:
fn for_each_planet<F>(f: F)
where F: Fn(&'static str) + 'static // `F` must now have "'static" lifetime
{
f("Earth");
f("Mars");
f("Jupiter");
}
fn main() {
let greeting = String::from("Good to see you");
for_each_planet(|planet| println!("{}, {}", greeting, planet));
// error: closure may outlive the current function, but it borrows
// `greeting`, which is owned by the current function
}What makes a closure 'static?#
for_each requires that the closure has static lifetime. but in main it just passes in a closure declared right there. it says “error: closure may outlive the current function, but it borrows”. what makes that closure have a static lifetime ?
Nothing does, and that’s exactly why it’s an error. The bound is a requirement the caller has to meet, and this closure doesn’t meet it. A closure is a struct holding whatever it captures. Reading greeting only needs a shared reference, so the closure borrows it:
struct Closure<'a> {
greeting: &'a String,
}F: 'static means the type holds nothing that could become invalid. Closure<'a> holds a borrow of a local in main, so it fails.
“It means the type holds nothing that could become invalid,” that should be true for any type :-)
Fair point, that was sloppy. In safe Rust nothing ever becomes invalid while you use it. What differs is how long the compiler lets you keep a value. A type with a borrow inside is confined to 'a, and it stays valid because it’s confined. A type without borrows (String, u32, a closure that owns its data) isn’t confined: you can store it in a global, send it to another thread, hand it to a task. So F: 'static means “F can be kept for as long as anyone wants”.
The call is rejected in main because the compiler checks the caller against the signature alone. The signature says for_each_planet may keep f around. It doesn’t matter that this particular body never does.
The fix is move, which captures the String by value. Now the closure owns its data and is 'static:
for_each_planet(move |planet| println!("{}, {}", greeting, planet));The same rule is why tokio::spawn requires 'static: a task can outlive whoever spawned it.
got it, thanks for the explanation.
I like that exchange because the first answer from Claude didn’t clear up my confusion, and the second answer hit home. “Holds nothing that could become invalid” was not specific enough for me. “How long the compiler lets you keep it” is what made it click.
Lifetimes are solved at the call site#
Next I read Pretzelhammer’s Common Rust Lifetime Misconceptions, which I highly recommend. Its snippets are short, and the comments in them are the content. After a while with misconception #3, I thought I had it:
parsing the snippet is useful, the comments there are enlightening after you think for a while. the actual lifetime is calculated at the call site. those lifetime annotations define the lifetime constraints under which the variables involved at the call site are allowed to pass the compiler checks.
so
// only takes ref types that can outlive 'a
fn t_ref<'a, T: 'a>(t: &'a T) {}the “t” reference needs to live at least as long as the scope of the call site, correct ?
The general insight is exactly right. One adjustment: not the scope of the call site, only 'a, and the compiler picks 'a as short as the constraints allow. Nothing in t_ref ties 'a to an output, so 'a is just the call:
let s = String::from("hi");
t_ref(&s); // 'a = this call
drop(s); // fine: the borrow already ended
An output tied to 'a is what stretches it:
fn first<'a, T>(items: &'a [T]) -> &'a T { &items[0] }
let v = vec![1, 2, 3];
let x = first(&v); // 'a must cover every later use of `x`
drop(v); // ❌ `v` is still borrowed…
println!("{x}"); // …because of this use
Swap the last two lines and it compiles. How the caller uses the result decides how long the borrow lasts. The signature only says what has to outlive what.
i see, got it.
This was the moment lifetimes clicked for me. I had been reading 'a as a name for some region of code, as if the function declared how long things live. It’s the other way round. A lifetime annotation is a constraint, like a type parameter is a placeholder, and the compiler solves the constraints at each call, picking the shortest lifetime that works.
It compiles, so the annotations are right?#
The same article has a misconception that I found even more interesting: “if it compiles, then my lifetime annotations are correct”. Here’s its byte iterator:
struct ByteIter<'remainder> {
remainder: &'remainder [u8],
}
impl<'remainder> ByteIter<'remainder> {
fn next(&mut self) -> Option<&u8> {
if self.remainder.is_empty() {
None
} else {
let byte = &self.remainder[0];
self.remainder = &self.remainder[1..];
Some(byte)
}
}
}That compiles. Then you use it:
let mut bytes = ByteIter { remainder: b"1123" };
let byte_1 = bytes.next();
let byte_2 = bytes.next(); // ❌ cannot borrow `bytes` as mutable more than once
if byte_1 == byte_2 { … }this example with the ByteIter was so interesting.
It’s lifetime elision. When a method’s return type has no lifetime, the compiler assumes the output borrows from self, so next really means:
fn next<'a>(&'a mut self) -> Option<&'a u8>That claims the byte lives inside the iterator, so byte_1 keeps bytes mutably borrowed, and the second next can’t borrow it again. But the byte lives in the slice the iterator points into, which outlives the iterator. One annotation says where the data really is:
fn next(&mut self) -> Option<&'remainder u8>The compiler only checks that annotations are consistent. Whether they describe where the data actually lives is up to you, and the default that elision picks can be stricter than it needs to be.
Claude also pointed out that my project has the mirror image of this. I wrote a frame reader that owns its buffer: it reads bytes from the network into the buffer and hands out complete frames. There, a reference into the buffer should be tied to &mut self, because the next read drains and refills that buffer. So the reader returns owned frames instead of references. The question is the same in both cases, and the answers are opposite: where do the bytes live?
Why bother#
At this point I asked the question I’d been circling the whole time:
this lifetime thing is the big safety win for rust, right ? controlling and checking reference validity. in c++ i can easily get into situations where i have a dangling reference.
Yes, but lifetimes are one of three rules, and the payoff comes from the combination:
- Ownership: every value has one owner and is dropped exactly once. No double free, no use after move. A moved-from C++ object is “valid but unspecified”. Touching a moved-from Rust variable is a compile error.
- Lifetimes: a reference can’t outlive what it refers to. A reference to a local, a
string_viewof a temporary, a lambda capturing by reference: all compile errors. - Aliasing XOR mutation: many
&Tor one&mut T, never both at once. This catches dangling references that lifetimes alone wouldn’t:
for (auto& x : v) v.push_back(x); // reallocation: x dangles
for x in &v { v.push(*x); }
// error[E0502]: cannot borrow `v` as mutable because it is also
// borrowed as immutable
The same rules cover threads. A data race is rule 3 across two threads, and the Send and Sync traits carry the rule across spawn.
What Rust doesn’t promise: leaks are “safe” (Rc cycles, mem::forget), and logic bugs, deadlocks and panics are still possible. The guarantees cover only safe code, since unsafe opts out. And the cost is that the checker is conservative, so you learn to shape your code so the proof is easy: owned data, indices instead of references, channels instead of shared state.
Here’s that “driving on the other side of the road” feeling again. In C++ I was used to running some sort of borrow checker in my head (well, at least attempting to). In Rust the compiler does it for me, but I have to shape the code to appease it. “Eat your vegetables, they’re good for you.” I’m starting to like these vegetables, but it’s too early to tell.