typestar

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.

Start this tour

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

Interior mutability

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.

The other Rust tours