Lifetime elision
Quick answer
Lifetime elision allows common reference relationships to be written without explicit names. Rust applies defined signature rules rather than examining the body to guess every relationship.
Elision rules
Each elided input lifetime is distinct. With one input lifetime, elided output references receive it. For methods with a borrowed self receiver, elided output references take the receiver lifetime. Otherwise an ambiguous borrowed output generally needs an annotation.
fn trim_name(s: &str) -> &str { s.trim() }fn main() { println!("{}", trim_name(" Kim ")); }Expected stdout (not executed):
KimThe output borrows from the only input.
Expected: compilation fails; exact diagnostic not verified.
Even though the body returns a, the signature must express which input supplies the output.
Common mistake
Do not assume the compiler uses the body to select an elided output lifetime.
Try it yourself
Rewrite trim_name with an explicit lifetime and fix the ambiguous function.
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
Lifetime elision — practice quiz
Choose one answer per question, then review the explanation.
What is the elided output lifetime in `fn prefix(s: &str) -> &str`?
Which rule applies to `fn name(&self, other: &str) -> &str`?
Why is `fn choose(a: &str, b: &str) -> &str` normally rejected?