LifetimesBeginner
1Question 1 of 1
rustWhat are Lifetimes in Rust and why does the compiler require lifetime annotations?
Explanation & Concept
Lifetimes ensure that references remain valid for as long as they are referenced. The borrow checker infers most lifetimes through **lifetime elision** rules.
When a function returns a reference derived from multiple input references, explicit lifetime annotations (`'a`) clarify which input parameter the output reference is linked to.
Code Example
rust
// Both inputs and return reference share the lifetime 'a
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let s1 = String::from("long string");
let result;
{
let s2 = String::from("short");
result = longest(s1.as_str(), s2.as_str());
println!("Longest is: {}", result);
}
}How It Works & Key Takeaways
Lifetime annotations do not change runtime duration; they inform the compiler how references relate so it can prevent dangling pointers.
Mock Test · 1 Questions · Optional
Ready for Error Handling (Result/Option)?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions