Recipe
Annotate a function that returns a reference
Use when: rustc reports E0106 on a function with two or more reference inputs and a reference output
Goal: a signature whose lifetimes say exactly which inputs the result borrows from
Taught in Annotating functions
Quick recipe
-
1
Read the body and list every input whose data can be returned, on any path.
Example
In
before(text, marker), both arms return part oftext. The list is justtext.Why: the signature has to describe what the body really does, and only you (not the compiler) read the body to write it.
-
2
Add
<'a>after the function name.Why: a lifetime parameter must be declared before the signature can use it, like
<T>. -
3
Write
&'aon each input from step 1 and on the returned reference. Leave the other inputs as plain&T.Example
fn before<'a>(text: &'a str, marker: &str) -> &'a strWhy: shared names say "the result is valid only while these inputs are"; an input left unnamed gets its own separate region.
-
4
An error in the body means it returns data the signature doesn't allow. E0597 at a call means a caller uses the result after an input is gone.
- error in the body — fix the body, or add that input to 'a if it really can be returned.
- E0597 at a call — fix the call: owner outward, use sooner, or copy.
Why: the signature is the contract both sides are checked against, so each error tells you which side broke it.
Common mistakes
- Putting
'aon every input by habit, which makes correct calls fail. - Changing the signature to silence an E0597 at a call site.
- Expecting
'ato keep an argument alive for longer.