Mutation and references#
Manuscript manages heap values through single ownership and lexical borrows, with no garbage collector and no named lifetime parameters.
How memory works#
Numbers, booleans and other primitives (Int, Float, Bool, Void, enums without payloads) copy freely, and .clone() on one returns the same value.
Everything else, including strings, types, lists and maps, has exactly one owner: a binding, a field, or a slot in another value. Scope exit releases values still owned there. Such a value is handed around by borrowing until you put it somewhere that must own it:
b := aandf(a)borrow:bandfreadain place, andais still yours afterwards.var b = aborrows exclusively, and so does passingato avarparameter, so changes reacha. The call writesf(a)either way (f(var a)is a parse error): the callee’s signature says which, as it does formove.- Storing a value in a field or a collection, returning a new value, or binding it at its last use moves it. After a move the old name is dead and the new owner frees it.
.clone()is the only way to copy. Write it when you want an independent value that outlives or diverges from the original. Borrowing lets a function work with existing data without a deep copy.
The compiler checks that borrows do not outlive their owners. While a borrow lives, the owner cannot change or be reassigned, and the borrow cannot escape the owner’s lifetime. Clone when a new owner needs to keep the data independently.
A function that returns a part of an argument says so in its signature: hold before the argument the result keeps using, and & before the result type. Wrapping a borrowed part in Optional or Result, or forwarding a borrowed error with ?, preserves that borrow, and the caller keeps the owner available while it uses the result. See the ownership rules
for the compiler contract.
Borrowing#
A borrow is a handle to a value that another binding owns. Until the borrow’s last use there may be many readers or one writer. Binding a place borrows it without a marker: x := a.b is a shared borrow and var x = a.b is an exclusive one. A loop variable and a match payload borrow the same way.
- A function can return a borrowed part of a parameter or receiver:
fn hold Box.list() &List[Int] { return self.items }. A binding of that result borrows the original place;xs := b.list()reads it andvar xs = b.list()changes it exclusively. A result without&is a new value, so a body that returns a part of any argument, held or not, without.clone()is an error: write&on the result for a held argument, or addholdand&for one that is not held. OptionalandResultcan carry borrowed payloads. When the relevant return paths borrow the payload,ok(self.name)orself.slots.get(i)keeps it borrowed;nullneeds no owner. AResultcan own its success value while borrowing its error from an argument, and?preserves the ownership of the active case. Clone a borrowed payload before storing it in a new owner.- A
&result must be a part of aholdargument on every return path; a part on one path and a new value on another is an error, so clone the part or make the new value aholdargument.&marks the payload of&T?and&T!, and it is never written at the top of a parameter type or at a call site. Interface operations and function types carryholdand&exactly as functions do, so a call through either borrows the way its signature says. - A call that borrows from a temporary must leave an owned result. It can move the whole temporary, but retaining a part requires a clonable result. To borrow a part of a non-clonable value, bind the argument first.
- A field owns its value unless it is written
&:items &List[String]looks at a list another binding owns. Building the record ties it to that value, so the owner cannot change, move or close while the record is used, and the record cannot outlive it, be returned without aholdsource, be stored in an owned place, be cloned, or be captured by a closure that outlives the statement. Assigning it to, or appending it to, a place that is used after the value’s block ends is an error too: declare the value before the place that holds the record. A record that holds such a record is tied the same way. The field stores the owner’s pointer, so nothing is copied and releasing the record leaves the value alone. - A place that is changed in place (a
varargument, avarreceiver, avarborrow, a closure that assigns) may not overlap any other operand or live borrow in the same call or scope.- Distinct fields (
var p.left,var p.right) and distinct non-negative literal list indexes (var xs[0],var xs[1]) are disjoint. Every other pair of element accesses (xs[i],xs[0]withxs[-1], map entries) may be the same element and is rejected, as is any change to the list itself while an element borrow is live. - A read that finishes before the change starts, such as an
Intargumentf(xs, xs[0])whereftakesvar xs, stays valid. - A method’s receiver and a function value held in a variable are read in place while the arguments run, so no argument (a
matcharm included) may reassign that variable; reassign before the call instead.
- Distinct fields (
type Box {
items List[Int]
}
fn hold Box.list() &List[Int] {
return self.items
}
fn grow(var b Box) Int {
var xs = b.list()
xs.append(1)
return b.items.length()
}grow returns the new length: xs borrows b.items through list, so append reaches b. var xs = b.list().clone() gives xs its own list.
The standard library writes the same marks: List.first, List.last, and Map.get borrow their element.
x := m.get(k)keepsmunchangeable untilxis last used, andx := m[k]borrows the entry directly (faulting when the key is missing).var x = m[k]borrows the entry exclusively so you can change it in place.- Bind a borrowed optional resource or function value with
v := xand testif v != nullto read it without moving it out of its container.
Moving into a function#
A signature says how a function treats each argument, and the body is checked against it; a caller never reads the body. A parameter borrows its argument unless the signature says move (the callee takes it) or hold (the result keeps using it). A body that stores, returns, or hands on a parameter without move is an error: write move, or keep .clone() of it. A move parameter is taken from the caller, and the caller’s name is dead after the call:
type Item {
name String
}
interface Sink {
fn add(move item Item) Int
}
type Log {
count Int
}
fn Log.add(move item Item) Int {
return item.name.length()
}
fn send(s Sink, move item Item) Int {
return s.add(item)
}move name Typesays the callee takes the argument;fn move Type.nametakes the receiver (move fn namein an interface). A caller writes nothing: the argument moves at its last use, and using it afterwards is an error.movemay be written on any function. Amoveparameter the body only reads is dropped when the body ends.- A type meets an interface operation only when its method writes
moveexactly where the operation does, as withvarparameters. - A function type carries
move,holdand&for its own parameters and result:fn(move Item) Intandfn(Item) Intare different types, and an anonymous function takes its modes from the expected type. A plain parameter of function type borrows its callback (the callee calls it without storing or returning it); a callee that stores or returns a callback writesmoveon that parameter (so closures passed there own their captures, while top-level functions pass freely to either).&fndoes not exist, so function-typed parameters take nohold. - The standard collections declare what they keep:
fn var List[T].append(move value T),Map.add(move key T, move value U),fn move BytesBuilder.build(). A method value has the same modes as the call, soxs.appendis afn(move T) Voidandappend(name)takesnamejust asxs.append(name)does. - A result is a new value unless the signature writes
holdand&. An implementation meets an interface operation only when it writesholdand&exactly where the operation does. moveandvardo not combine on one parameter.
Reassignment#
- A
:=binding cannot be reassigned, and neither can a resource held in one. - Reassigning an owning
vardrops its previous value and closes any resources it held. Scope-end cleanup then closes its final value. Closing early withclose()moves the value, so scope end has nothing left to close. See scope-end cleanup . - A live borrow prevents reassignment.
- Every binding is initialized at declaration, and an outer
varkeeps its declared type. - Non-escaping closures borrow their captures. Escaping closures own them, so a function moves a parameter that an escaping closure captures; the caller passes
.clone()to keep the value. - Borrowed roots cannot be changed or moved while the borrow is live.
See bindings , closure captures , and scope-end cleanup .
Index assignment#
place[key] = value is a call of the type’s set (a Map’s add). The checker takes the key at the store, after value has run, so value may read key: counts[key] = counts.get_or(key, 0) + 1 and sizes[k] = k.length() are accepted.
value may only read key; it cannot move or change it (m[k] = bump(k) is rejected when bump takes var k). After the store, key cannot be used unless it is a scalar or the store used a .clone() of it.
Data copies#
.clone() is a deep copy of nested values. Opaque handles and function values have no clone and are never copied, and a value that holds one is not Clonable either. See mutation and cloning
.
Sharing a value#
There is no shared mutable value. A value has one owner; a promise reads what it captures, and changes travel as messages over a pipe to the owner. See concurrent tasks
.
References inside other values#
Fields and collection slots own their values. Moving a resource into one transfers the cleanup duty to the holder. At scope end, a holder closes the resources it owns, including nested parts. Its own Closeable.close, if present, runs before its parts. See the close-order table
.
A borrow of a resource field keeps the holder available and prevents closing or changing it while that borrow is still used. Destructuring transfers only the fields that move out; omitted resource fields are still closed. A resource field of a mutable holder moves out only when the next statement refills it (part := holder.field, then holder.field = ...); otherwise move the whole holder.
Memory and open resources#
Owned values are dropped deterministically; there is no tracing garbage collector. Releasing a file, socket, or other external resource is separate. Use close(), or let the scope that owns the resource close it.
A borrow keeps its owner available until the borrow ends, but it does not extend the lifetime of the external resource. close() is a move method, so it takes the resource like any move: the name is moved afterwards. A borrow takes on no cleanup duty; an owning closure or promise does take on the duties of the resources it owns.
Returning a resource#
A factory returns an open resource by moving it to the caller. Returning a locally owned resource transfers its cleanup duty; the factory does not close the moved value on its way out. A resource left owned by a local binding closes when that scope ends. A borrow cannot escape a local owner that is about to close.
A use after close() is a use after move, a compile error. A handle another owner still holds, such as a clone of a file handle, returns its closed-state error after it is closed.
See Closeable , scope-end cleanup , and closures .