Lifetimes
| Elision covers most | |
| One named lifetime (&'a form) | |
| Static strings | |
| Read compiler hints |
Elision covers most
Most functions need no lifetime names because the compiler fills them in. A function that takes one shared borrow and returns one shared borrow just works:
fn first(s: &str) -> &str {
s
}
One named lifetime (&'a form)
When two borrows enter and one borrow leaves, name the relationship once. Both inputs and the output share the same name to show they live together:
fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Static strings
String literals live for the whole program and use the static lifetime. A static borrow never expires while the program runs:
let s: &'static str = "hello";
Read compiler hints
When a lifetime is missing, the compiler suggests one exact spot to add it. Read the hint, add the name, and keep the change small:
let s = String::from("hi");
let r = s.as_str();
println!("{}", r);
Next: Functions
Article author: Arthur Isaev