Lifetimes#
A lifetime 'a is a region annotation telling the compiler
how long a reference must remain valid. Often elided; explicit
when ambiguous.
Function with two borrowed inputs that share a lifetime.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
Struct with a borrowed field; the struct cannot outlive the borrow.
struct Holder<'a> { name: &'a str }
The static lifetime 'static lasts the whole program
(string literals, static items).
let s: &'static str = "hello";
References#
References for the borrow forms
'adescribes.Generics for combining type and lifetime parameters.