Sub topic 3
When Lifetimes Can Be Omitted
Assume you know ownership, String, Vec, references, and basic functions. Rust uses lifetime annotations to describe how long references remain valid. Lifetime elision means the compiler applies common rules so you can omit annotations when their meaning is clear.
Elision and Structs That Borrow
This function has one input reference, so Rust gives the output reference the same lifetime as that input:
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}A struct that stores a reference still needs an explicit lifetime parameter:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let text = String::from("Rust is fast");
let excerpt = Excerpt { part: &text };
println!("{}", excerpt.part);
}'a does not extend the data's lifetime. It tells the compiler that Excerpt cannot outlive the borrowed text.
Reborrowing Mutable References
A mutable reference can be temporarily borrowed again. Each function call below receives a short reborrow, so r remains usable:
fn add_one(values: &mut Vec<i32>) {
values.push(1);
}
fn main() {
let mut values = Vec::new();
let r = &mut values;
add_one(r);
add_one(r);
println!("{r:?}");
}Choosing Borrow, Move, or Clone
| Choice | Use it when | Effect |
|---|---|---|
| Borrow with `&T` | The function only reads | Caller keeps ownership |
| Move with `T` | The function should own the value | Caller cannot use it afterward |
| Clone with `.clone()` | Independent owned data is needed | Copies the value |
Prefer borrowing when ownership does not need to change. Clone only when the separate owned value is worth its cost.
Interior Mutability
RefCell<T> permits mutation through a shared reference. It checks borrowing rules at run time rather than compile time.
use std::cell::RefCell;
fn main() {
let data = RefCell::new(vec![1]);
data.borrow_mut().push(2);
println!("{:?}", data.borrow());
}Conflicting borrows cause a run-time panic, so use RefCell only when compile-time borrowing cannot express the design.
Reading Common Errors
E0502 means shared and mutable borrows overlap:
fn main() {
let mut values = vec![1, 2];
let first = &values[0];
values.push(3);
println!("{first}");
}The fix is to finish using first before calling push, or copy the needed value first.
Exercise
Why does fn first_word(s: &str) -> &str compile without a lifetime annotation?
Show answer
Elision assigns the output lifetime to the function's single input reference.