Lesson 3 of 9 · 25m
Lifetimes Without Fear
Read lifetime annotations as dataflow statements, recognize when elision is enough, and design around borrowing instead of fighting it.
Lifetimes have an undeserved reputation because people meet them as syntax before meeting them as dataflow. A lifetime annotation does not make a value live longer. It tells the compiler how references in inputs and outputs are related. Once you read 'a as "this output is derived from that input," most of the fear drains away.
Lifetimes describe, they do not extend
This annotation means the returned slice is borrowed from input:
fn token_before<'a>(input: &'a str, delimiter: char) -> &'a str {
input.split(delimiter).next().unwrap_or("")
}Nothing in 'a extends input. The annotation merely prevents the caller from using the returned token after input is gone. If you want the value to outlive the input, return an owned String; no lifetime trick can manufacture ownership.
Elision handles the boring cases
You usually do not need explicit annotations for one-input borrowing:
fn len_bytes(s: &str) -> usize {
s.len()
}The compiler applies lifetime elision rules. Add explicit names when relationships become ambiguous or when the names communicate architecture. A good rule for teams: write explicit lifetimes where dataflow is subtle, not everywhere out of superstition.
Struct lifetimes are contagious
This type is zero-copy but binding:
struct HeaderView<'a> {
name: &'a str,
value: &'a str,
}Every function returning or storing HeaderView<'a> now carries that lifetime. That may be correct inside a parser hot loop. It is usually wrong at module boundaries, network tasks, caches, and error reports. Contain borrowed views near the parse site, then convert to owned data before escaping:
struct Header {
name: String,
value: String,
}
impl<'a> HeaderView<'a> {
fn to_owned(&self) -> Header {
Header { name: self.name.into(), value: self.value.into() }
}
}Common lifetime traps in real systems
The recurring failures are practical:
returning references into a local buffer
storing references into a struct that owns the buffer
retaining references across await points
reusing a mutable buffer while old slices still point into it
keeping references into memory owned by a callback or FFI callThe self-referential struct is the classic trap: Rust does not let you store a buffer and references into that buffer in the same ordinary struct because moving the struct would invalidate the references. Restructure the data or use an established arena/index design; do not reach for unsafe because the model is inconvenient.
Design pattern: indexes beat self-reference
Instead of storing slices into a shared buffer, store owned buffers plus offsets:
struct Packet {
bytes: Vec<u8>,
header_range: std::ops::Range<usize>,
}
impl Packet {
fn header(&self) -> &[u8] {
&self.bytes[self.header_range.clone()]
}
}This preserves zero-copy parsing without making the struct self-referential. The borrow is created at use time, where the compiler can verify it.
Field notes
- Lifetime errors often appear far from the design mistake; trace which value is expected to outlive which owner.
- Long lifetime parameter lists are usually a sign that borrowed types escaped their intended scope.
Box::leakcreates'staticdata by leaking memory. It can be justified for immutable process-lifetime configuration, not as a general escape hatch.- If async code makes borrowed data painful, decide whether the value truly crosses a task boundary. If it does, own it or share it explicitly.
Was this lesson helpful?