Skip to content

Memory model

Ownership and borrowing in the style of Rust:

  • Every value has one owner; assignment and passing by value move.
  • &T shared borrows, &mut T exclusive borrows; mutation is visible at the call site.
  • Immutable by default: let vs let mut.
  • No lifetime syntax. Returned references must derive from a parameter (Rust’s elision rules, made mandatory). Structs, enums and collections can hold references; a value holding one borrows what it refers to, like a plain reference does (see below).
  • Copy is structural: i64, bool, &T, and structs/enums made only of Copy parts are copied. Everything else (Str, Vec, Map, Box, &mut T, and anything containing them) moves.
  • Using a value after it moved is an error, including after a move in only one branch, or a move inside a loop of a value declared outside it.
  • Moving out of a reference or out of a Vec element is an error; use .clone(). Every type has .clone(), a deep copy.
  • Passing a &mut T on reborrows it rather than moving it.
  • + on strings, and string methods, only read their operands.
  • Borrows: while a reference to a place is still used later, the place cannot be changed, moved or mutably borrowed, and while a &mut reference is still used, the place cannot be used at all. A borrow ends at the last use of the reference (like Rust’s non-lexical lifetimes); a reference declared outside a loop and used inside it lives through the loop. A for loop over &v borrows v for the whole loop.
  • A method’s &mut self borrow starts only after its arguments are evaluated (two-phase borrows), so v.push(v.len()) works.
  • Two arguments of one call cannot borrow the same place if one of the borrows is mutable.
  • References returned from a function must point into its parameters, never into its locals. References returned from a method borrow the receiver.
  • A value that holds references (Cursor { text: &line }, [&a, &b], Found.At(&s)) borrows everything they point at. Storing a reference into a variable’s contents (v.push(&s), h.name = &s, a &mut self method or &mut argument given a reference) makes that variable borrow it too. Something reached through a &mut parameter cannot be given a reference to the function’s own locals.
  • A variable cannot end while something declared outside its block still refers to it and is used later: r = &s inside an if, with r read after it, is an error. “Used later” means read before being overwritten: a holder given a new value (r = &a) before its next read no longer holds the old loan, both for this check and for the borrow checks above. An overwrite inside only one branch of an if does not count.