Lifetime Basic
Annotate references with lifetime parameters.
Lifetime Basic
Annotate references with lifetime parameters.
Difficulty
Advanced
Code
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("xyz");
result = longest(s1.as_str(), s2.as_str());
println!("longest: {}", result);
}
}Explanation
Lifetimes tell the compiler how long references are valid.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the lifetimes category to build a complete understanding of this topic.