Memory model
Ownership and borrowing in the style of Rust:
- Every value has one owner; assignment and passing by value move.
&Tshared borrows,&mut Texclusive borrows; mutation is visible at the call site.- Immutable by default:
letvslet 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
Vecelement is an error; use.clone(). Every type has.clone(), a deep copy. - Passing a
&mut Ton 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
&mutreference 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. Aforloop over&vborrowsvfor the whole loop. - A method’s
&mut selfborrow starts only after its arguments are evaluated (two-phase borrows), sov.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 selfmethod or&mutargument given a reference) makes that variable borrow it too. Something reached through a&mutparameter 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 = &sinside anif, withrread 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 anifdoes not count.