Lifetimes
A lifetime is the span for which a reference is valid. The compiler names it 'a in signatures when a returned or stored reference must not outlive its source.
Detailed Explanation
&'a str means "a string slice that lives at least 'a". Lifetimes are not garbage-collection roots. They are compile-time names for regions of the stack (and of 'static data). You write them when the compiler cannot guess the relationship between inputs and outputs.
fn first(s: &str) -> &str is fine: elision assumes the output borrows from the single input. fn longest(a: &str, b: &str) -> &str is not fine: the compiler does not know whether the result comes from a or b. You write fn longest<'a>(a: &'a str, b: &'a str) -> &'a str, which says both inputs and the output share one lifetime — the shorter of the two at the call site.
Structs that store references need a lifetime parameter: struct Line<'a> { text: &'a str }. Line cannot outlive text. If that is painful, store a String. Lifetime parameters are the cost of avoiding that allocation.
Lifetimes do not change the generated machine code. They are erased. A wrong lifetime is a compile error, not a slower program. 'static is the lifetime of the whole process: literals, leaked boxes, and data that truly never dies. It is not a magic way to hide a borrow; a local String is not 'static.
When you write 'a: returning a reference, storing a reference, or tying two borrows together. When you do not: most functions with one reference input, and most code that owns its data. If a lifetime annotation is fighting you, the design may want an owned value.
Code Examples
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let a = String::from("ada");
let b = String::from("grace");
println!("{}", longest(&a, &b)); // prints: grace
}Common Gotchas
Returning a reference to a local does not compile
The local is dropped. Return an owned `String`, or take a buffer to write into.
`'static` is not a promotion
`&local as &'static` is a lie. Leak, or own, or keep the real lifetime.
Elision covers the common one-input case
You will write lifetimes when there are two inputs or a stored reference, not on every function.
The name `'a` is arbitrary
`'input` and `'src` are legal and sometimes clearer. The meaning is the relationship, not the letters.