Annotate function lifetimes
Quick answer
Named lifetime parameters express how borrowed outputs relate to inputs. Use them when Rust cannot infer the relationship from a function signature alone.
Relate inputs and output
fn pick<'a>(a: &'a str, b: &'a str) -> &'a str promises that the returned reference is usable within the common valid borrowing region. The caller cannot use it beyond either input's required lifetime. If the result only borrows a, give b an independent lifetime instead.
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b }}fn main() { println!("{}", longer("cat", "horse")); }Expected stdout (not executed):
horseBoth inputs can supply the result; len here counts bytes, and the inputs are ASCII.
fn first<'a>(a: &'a str, _: &str) -> &'a str { a }fn main() { let outer = String::from("keep"); let result; { let short = String::from("temp"); result = first(&outer, &short); } println!("{result}");}Expected stdout (not executed):
keepThe output is tied only to outer.
Common mistake
Lifetime annotations cannot make a reference to a local String escape safely.
Try it yourself
Change first to return the second parameter; identify the signature change needed.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Annotate function lifetimes — practice quiz
Choose one answer per question, then review the explanation.
In `fn left<'a>(a: &'a str, b: &str) -> &'a str`, which input constrains the declared output?
Can a function returning either input promise an output that outlives the shorter required input?
What does `'a` stand for in a borrowed signature?