Describe the relationship.
Connect returned references to the data they borrow.
01 Understand the contract
Lifetime annotations describe relationships between borrows; they do not extend how long a value lives. When a function may return a reference into either of two inputs, an explicit lifetime can say that the result is usable only while the necessary input borrows remain valid. Many common signatures use lifetime elision rules and need no annotation. An owned return is often simpler when the result must live independently. A static string literal is valid for the entire program; a borrowed local String is not.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn longer<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() {
left
} else {
right
}
}
fn main() {
let first = String::from("compiler");
let second = String::from("cargo");
println!("{}", longer(&first, &second));
}compiler
- 1
The same lifetime parameter connects both input references and the output.
- 2
The annotation does not allocate or prolong either String.
- 3
This comparison uses byte length as its explicit metric.
cargo run -p lesson_lifetimes03 Mind the boundary
04 Your next build
Define a borrowed Label struct with a lifetime and return its text through a method.
Reveal one possible solution +
struct Label<'a> {
text: &'a str,
}
impl<'a> Label<'a> {
fn text(&self) -> &str {
self.text
}
}
fn main() {
let value = String::from("ready");
let label = Label { text: &value };
assert_eq!(label.text(), "ready");
}05 Check your reasoning
Do lifetime annotations keep a local allocation alive longer?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.