What are lifetimes in Rust?
Answer
Lifetimes are Rust's way of tracking how long references are valid. Every reference in Rust has a lifetime — the scope during which the reference must remain valid. Most of the time the compiler infers lifetimes automatically through lifetime elision rules, so you do not need to annotate them. Explicit lifetime annotations are needed when the compiler cannot infer them — typically in functions that return references or in structs that hold references. The syntax is 'a (a tick followed by a name): fn longest<'a>(x: &'a str, y: &'a str) -> &'a str. Lifetimes prevent dangling references — the borrow checker uses them to verify that returned references are always valid for as long as they are used.
Previous
What is the borrow checker in Rust?
Next
How do you define structs and impl blocks in Rust?