Lifetime annotations in Rust
When a function returns a reference, the compiler needs to know which input it borrows from.
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() {
a
} else {
b
}
}
fn first_line<'a>(text: &'a str, fallback: &'a str) -> &'a str {
text.lines().next().unwrap_or(fallback)
}
fn main() {
let title = String::from("Lifetimes");
println!("{}", longer(&title, "short"));
println!("{}", first_line("one\ntwo", "empty"));
}
How it works
<'a>declares a lifetime, then names it on the references.- The return value may not outlive the inputs it came from.
- The annotation describes the relationship; it never changes it.
Keywords and builtins used here
Stringelsefirst_linefnifletlongermainstr
The run, in numbers
- Lines
- 17
- Characters to type
- 343
- Tokens
- 145
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.
Step 1 of 4 in Lifetime annotations, step 1 of 11 in Lifetimes & interior mutability.