Sub topic 3
Dangling References, Lifetimes, and Shared Ownership
Assume basic Rust syntax, String, Vec, references, and Cargo. A reference must never outlive the value it points to. A reference that outlives its value is a dangling reference. Rust rejects one at compile time instead of allowing use-after-free at runtime.
Lifetime annotations
A lifetime annotation names a relationship between references. It does not make a value live longer.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let first = String::from("long text");
let second = String::from("short");
println!("{}", longest(&first, &second));
}Here, 'a says that the returned reference is valid for no longer than both input references. Rust can therefore reject code that returns a reference to a local variable after that variable has been dropped.
Lifetime elision
Rust often infers lifetimes through lifetime elision rules:
- Each input reference gets its own lifetime.
- If there is one input reference, its lifetime is assigned to the output.
- For methods, the output lifetime usually comes from
&selfor&mut self.
Thus, this function has the same meaning as a version with an explicit lifetime:
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}Structs that hold references
A struct containing a reference also needs a lifetime parameter:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let text = String::from("Call me Ishmael.");
let excerpt = Excerpt {
part: text.split('.').next().unwrap(),
};
println!("{}", excerpt.part);
}The annotation prevents Excerpt from outliving text.
Owning heap data with `Box`
Box<T> owns a T stored on the heap. It is useful for recursive types or when heap allocation is required. Dropping the box drops its value.
Multiple owners and controlled mutation
Rc<T> provides shared ownership within one thread. RefCell<T> allows mutation through a shared owner, checking borrowing rules at runtime.
use std::{cell::RefCell, rc::Rc};
fn main() {
let data = Rc::new(RefCell::new(vec![1]));
let other = Rc::clone(&data);
other.borrow_mut().push(2);
println!("{:?}", data.borrow());
}A conflicting borrow_mut and borrow causes a runtime panic.
Ownership across threads
Arc<T> is the thread-safe form of shared ownership. Pair it with Mutex<T> when threads must mutate shared data.
Exercise
Why can a lifetime annotation reject a dangling reference but cannot extend the referenced value's lifetime?
Show answer
It describes an existing validity relationship. The referenced value still determines when the reference becomes invalid.