v0.4.0

References

A reference lets code use a value that belongs to someone else, without copying it and without taking it over. &T is a shared reference: it can read the value. &var T is an exclusive reference: it can read and write it. A reference never owns its referent, is never null, is never pointed at other storage, and lives no longer than the call or the block that made it.

reference-type = "&" type
               | "&" "var" type
struct Account {
    owner: char8[..];
    balance: int;
}

func Report(account: &Account) {
    PrintLine("{}: {}", account.owner, account.balance);
}

func Deposit(account: &var Account, amount: int) {
    account.balance += amount;
}

func Main() -> int {
    var alice = Account { owner: "alice", balance: 10 };
    Deposit(alice, 5);   // borrowed for writing: alice.balance is now 15
    Report(alice);       // borrowed for reading
    return 0;
}

References are the safe way to share. A raw pointer is an address the program vouches for itself; a reference is one the compiler checks, under the rules on Exclusivity.

Borrowing is implicit

There is no borrow operator. A reference is made — the value is borrowed — when a place is given where a reference is expected:

  • an argument for a parameter of type &T or &var T;
  • a receiver: calling a method declared with &self or &var self borrows the value it is called on;
  • a binding annotated with a reference type: let shared: &Account = alice;.

The call site looks the same as passing by value; the parameter's type decides. & is never an operator, and writing it before a value is an error that points to @, which takes a raw address:

error: '&' does not take an address; write '@' to take the address of a value

What is borrowed must be a place — a variable, a field, an element, or the referent of another reference. A literal or a freshly built value has nowhere to be borrowed from, so Report(Account { owner: "x", balance: 1 }) and Bump(5) — Bump is defined below — are rejected:

error: argument 1 to 'Report' has type 'Account', but parameter 'account' requires '&Account'
error: argument 1 to 'Bump' has type 'int', but parameter 'count' requires '&var int'

An exclusive borrow also needs a place that may be written. With let savings = Account { … };, Deposit(savings, 10) is rejected:

error: argument 1 to 'Deposit' cannot borrow immutable 'savings' as '&var Account'
  help: declare 'savings' with 'var' to make it mutable

A &var T is accepted wherever a &T is expected: an exclusive reference can always lend reading.

Using a reference

A reference is used as if it were the value. Fields, methods, indexing and .length all reach through it with no * and no arrow:

func First(values: &int[3]) -> int {
    return values[0] + values.length as int;
}

A reference to a scalar — an integer, a float, a bool, a character — supplies the scalar's value wherever a value is expected: in arithmetic and comparisons, in a condition, in a cast, in an assignment or a typed binding, as a by-value argument:

func Twice(value: &int) -> int {
    return value * 2;
}

To copy a scalar out of a reference, give the binding its type: let saved: int = value;. * is a raw-pointer operator and never applies to a reference:

error: operator '*' requires a pointer operand, but found '&var int'
  note: a reference reads and writes its referent without '*'
  help: write 'r' in place of '*r', as in 'r += 1'

Writing through &var

Through a &var T the referent can be written in three ways.

Fields and elements are written as usual: account.balance += 5, values[i] = 0.

A scalar referent is written by assigning to the reference itself. =, the compound assignments and ++/-- all store into the caller's value:

func Bump(count: &var int) {
    count += 1;
}

func Main() -> int {
    var total = 4;
    Bump(total);                 // total is now 5
    let alias: &var int = total;
    alias = 20;
    alias++;                     // total is now 21
    return 0;
}

Any other referent — a struct, a tuple, an array, a value of a type parameter — is replaced whole with =. This is how a method replaces the value it was called on:

extend Account {
    func Reset(&var self) {
        self = Self { owner: self.owner, balance: 0 };
    }
}

The write follows the assignment rules for T exactly as an assignment to a var local would: the new value is produced first, the old one is destroyed, and the new one is installed; a move-only value needs move or an explicit Clone(). Compound assignment and ++/-- apply to scalar referents only, and an interface view cannot be replaced, because its referent's type is not known.

Through a shared reference every write is an error:

error: cannot modify data through immutable reference '&Account'

A reference is never reseated

= through a reference always writes through to its referent; nothing points a reference at other storage. A reference local is therefore declared with let, and a var binding of reference type, written or inferred, is an error:

error: 'var' binding 'alias' cannot hold reference '&var int'
  help: references cannot be reseated; use a pointer or a new binding

To refer to another value, declare a new binding.

Returning a reference

A function may return &T, &var T, or the optional reference &T?, with no lifetime written anywhere: the signature alone says what the result borrows from. It is the receiver when the function takes one by reference, &self or &var self; otherwise it is the one parameter that is a reference or a slice:

struct Slots {
    items: int32[4];
    count: uint;
}

extend Slots {
    func At(&self, index: uint) -> &int32 {
        return self.items[index];            // borrows self
    }

    func AtMutable(&var self, index: uint) -> &var int32 {
        return self.items[index];
    }

    func Find(&self, index: uint) -> &int32? {
        if index >= self.count { return none; }
        return self.items[index];            // made present
    }
}

func First(items: int32[..]) -> &int32 {
    return items[0];                         // the only slice parameter
}

A receiver taken by value lends nothing, and neither does a variadic parameter. Any other signature — two reference parameters, or none — is cannot tell what the returned reference borrows from, with help: return an owned value. An operator, [] included, cannot return a reference, so an accessor that lends an element is a method such as At.

Every return yields a reference derived from the source: the source itself, a field or element of it, a reference a call returned from it, or a local reference holding one of those. A reference to a local is cannot return a reference to local 'copy', one to a by-value parameter cannot return a reference to parameter 'value', one to a temporary is cannot return a reference to a temporary value, and one borrowed from another reference parameter is cannot return a reference borrowed from 'other'. &var T needs storage the function may write, so a method taking &self cannot return a &var to its fields.

At the call site the result is a reference like any other: it lives in a let local, is passed on to a reference parameter, or is returned again under the same rule. A scalar is read from it as from any reference, so let first: int32 = slots.At(0); copies the value. While the result is in use, the argument it borrows from is borrowed — a &T result keeps it from being written or moved, and a &var T result from being used any other way, until the result's last use. That argument must be storage that outlives the statement, so Make().At(0) is the returned reference would borrow from a temporary value. A function value never returns a reference: calling one whose type would is cannot call a function value that returns reference '&int32'.

An optional reference &T? — the suffix after the referent; &(T?) is a reference to an optional — may be a return type and the type of a let local, and nothing else. found ?? fallback yields a reference, so the fallback is a place or a reference too, or leaves, as ?? return does; if found is .Some(value) and a match arm .Some(value) bind a reference. ? does not propagate the absence of an optional reference; match it, or use ??.

Where a reference may appear

A reference is a non-owning alias for the length of a call or a block, so it may appear in exactly four places: a parameter, a receiver, a let local, and the result of a function whose signature says what it borrows from, as above. It cannot be stored in a field, an array or a tuple, or moved out of — a field r: &int in a struct Holder and let mine = move account; on a reference parameter are rejected in turn:

error: field 'r' in struct 'Holder' cannot store reference type '&int'
  note: references are non-owning aliases and cannot escape into aggregate storage
  help: store the owned value or a raw pointer when an address must outlive the borrow
error: cannot move a non-owning reference
  note: references borrow storage but do not own the value they address

A reference is no type argument either, written or deduced. A generic body is checked once for whatever its parameter stands for, so nothing there proves it does not store the value — Thread::Spawn keeps its context for the new thread — and Hold<&Counter>(counter) is refused, as is Spawn(ByRef, counter) with func ByRef(counter: &Counter):

error: type argument '&Counter' of function 'Hold' cannot be or hold a reference
  note: type parameter 'T' may be stored by the generic code, and a reference cannot outlive the call that borrowed it
  help: pass an owned value, or a raw pointer when the address must be shared

A reference cannot destroy its referent either: replacing a value through &var T installs a new one in its place. When an address must be stored or must outlive the call, use a raw pointer.

References and pointers

&T, &var T*T, *var T
Made byan implicit borrow@place
Nullnevernull is a value
Read and writeas the value itself*p; p.field and p[i] reach through, inside unsafe
Arithmeticnonep + n, p - n, inside unsafe
Stored in a fieldnoyes
Returnedwhen the signature names its sourceyes
Checkedexclusivity, writabilitywritability only

A reference is 8 bytes, the size of the address it holds.

See also