advancedLifetimes
Lifetime Elision
Understand Rust lifetime elision rules.
Lifetime Elision
Understand Rust lifetime elision rules.
Difficulty
Advanced
Code
rust
// Rule 1: each reference gets its own lifetime
fn first(s: &str) -> &str {
// elided: fn first(s: &str) -> &str
s.split_whitespace().next().unwrap()
}
// Rule 2: if there is one input lifetime, it is assigned to all outputs
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
// Rule 3: methods with &self, the lifetime of self is assigned to all outputs
struct Parser {
input: String,
}
impl Parser {
fn next_token(&self) -> &str {
self.input.split_whitespace().next().unwrap()
}
}
fn main() {
let s = String::from("hello world");
println!("first: {}", first(&s));
println!("word: {}", first_word(&s));
let p = Parser { input: s };
println!("token: {}", p.next_token());
}Explanation
Elision rules automatically infer lifetimes in common cases.
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.