Lifetimes & interior mutability
11 steps in 5 sets of Rust.
The annotations most people avoid until they cannot. Lifetimes are not a separate feature bolted on; they are the borrow checker's notation, and reading them is mostly a matter of getting used to the syntax.
Then borrowing without copying, interior mutability with Cell and RefCell for the cases where the rules need bending safely, and storing behavior in a struct. Eleven steps, and it is the tour that makes the error messages start making sense.
Lifetime annotations
- Lifetime annotationsWhen a function returns a reference, the compiler needs to know which input it borrows from.
- Structs that borrowA struct holding a reference carries a lifetime, tying it to the data it reads.
- Elision rulesMost signatures need no annotation, because three rules infer the obvious case.
- The 'static lifetime'static means the reference is valid for the whole program, not that the value never moves.
Borrowing without copying
- Cow: borrow until you must ownClone-on-write returns a borrow when nothing changed and an owned value when it did.
- Returning a borrowing iteratorAn iterator over borrowed data ties its lifetime to the collection.
Interior mutability
- RefCell and interior mutabilityRefCell moves the borrow check to run time, so a shared value can still be mutated.
- Rc<RefCell<T>>Shared ownership plus interior mutability: several handles onto one mutable value.
- Weak references break cyclesA child pointing back at its parent must do so weakly, or nothing is ever freed.
Stored behavior
- Storing closuresA closure has an unnameable type, so a struct stores it boxed behind Fn.
Encore
- tokenizer.rsA zero-copy tokenizer: every token is a slice into the original source.