Lifetimes in Rust
It was always there, but now it's explicit
Recap: References
&MyStruct
is a reference/borrow of a struct
- If the underlying struct is removed, the reference is invalid
- In C++, it is entirely on you to manage this
- Rust just makes this management explicit
Motivation
let x;
{
let y = 5;
x = &y;
} // uh oh
println!("x: {}", x); // hmmm
Rust will not compile this code
Lifetimes
- These always exist.
- Sometimes the compiler needs some hints
- We can annotate lifetimes to add hints
Annotation Example
The borrow checker will use the shortest lifetime
Challenge: Circular references
Rc + Refcell
- + safety of ownership/mutability at runtime
- - there is a performance penalty
- - a bit awkward to use.
Vec + Index
- + fast, no weird Rc stuff
- - bug prone, self managed, can dangle
3rd party libraries
slotmap: Like a hashmap, but with unique keys
typed-arena: Arena allocator. Can only drop the whole arena