^T is the one owning pointer: ^Point{ … } allocates a block of its own.
&p borrows storage that already exists — a local, a field, an element — and
is a &T, or a pointer into that storage where a ^T is asked. Each arrives
as a single address, and the difference between them is how long the storage
lasts.
The surface — ^T, &, x.^, ^T? — is on
Pointers. This page is the rule about where one
may travel.
Every example here is compiled and executed by the compiler’s own test suite, and its heap is checked back to zero.
Two provenances, one rule
A reference into a block may go anywhere. Returned, stored in a field, put in a collection, captured by a closure that escapes. The block stays alive because the reference keeps its count.
struct Point { x int, y int }
fn make(n int) ^Point {
return ^Point { x: n, y: 0 }
}
fn main() int {
p: ^Point = make(7)
return p.x
}A reference into a frame lives as long as that call does. It may be read,
and it may be lent to a callee, because the callee’s activation is contained in
this one. It may not be returned (ATOLL1122, said where the reference is
taken), stored into a block, or captured by an escaping closure:
fn escape() ^int? {
n: int = 7
return Some(&n) // `n` dies with this frame
}
fn main() int {
return match escape() { Some(p) => p.^ None => 0 }
}There is no annotation that makes that safe, and no promotion that quietly
moves n to the heap to allow it. A reference that must outlive the frame is
one you write as ^T{ … }.
A value that owns a block (a string, a list, a struct holding one) releases
it as the function ends, so a reference to it is held to the same rule when it
is returned (ATOLL1116), however it reaches the return: taken there, bound
to a name first, or handed back by a call it was lent to. Kept in a &mut
parameter’s place (out.push(&s), h.r = &s), it is refused where it is
kept: that place is the caller’s, and outlives the call.
fn greeting() &string {
s := "hello".repeat(2)
r := &s
return r // `s` is released as `greeting` ends
}
fn main() {
println(greeting())
}Return the value itself, which moves it out, or .clone() a borrowed one.
A &mut parameter is a reference into the caller’s frame, so it is held to the
same rule at the place the source can point to: a closure that captures one and
is returned or stored is ATOLL1112, and one call that borrows a place twice
with a &mut among the borrows is ATOLL1113. Both are on
Pointers.
Neither guess is the safe one, which is why the declaration carries the fact rather than an inference. Treat a frame reference as though it named a block and the increment lands on the frame’s own storage, which the epilogue reclaims anyway — a dangling pointer arrived at by way of the count that was supposed to prevent one. Treat a block reference as though it named a frame and no count is taken at all, so the block dies under it.
An option does not launder it
Wrapping a reference in Some(…) and taking it back out of a match is free —
^T? is one word with null standing for None — and it changes nothing about
where the reference may go. Inside the frame it works:
fn main() int {
n: int = 7
held: ^int? = Some(&n)
return match held { Some(p) => p.^ None => 0 }
}Carrying one out of the frame is the same escape and is refused the same way
— that is what the return Some(&n) above is. The wrap is not a conversion; it
is the identity on a word, so there is nothing for it to launder.
A join takes the target its edges agree on
Two arms producing a reference must agree about what kind of storage they name. Two frame references agree, so this compiles:
fn main() int {
a: int = 3
b: int = 4
c: bool = true
p: ^int = if c { &a } else { &b }
return p.^
}So do two separately allocated blocks — different allocations, same answer to what does a release act on. What has no answer is one arm naming a frame and the other a block: a release sent to either would touch storage the other path never had. That program is refused at the boundary rather than guessed at:
atoll run: the module would not encode: NotYetEmitted("a reference count
on a pin whose target nobody stated — a `&place` or a `^T{...}` states
one, and a join states one only when every path agrees")Absence is not a disagreement. match &xs.get(i) { Some(p) => p None => None }
has one arm naming storage and one naming nothing, and a null constrains
nothing, so the join takes the other arm’s answer.
A store releases what the place held
Writing over a place releases its previous occupant, not the value replacing
it. That includes writing None over an owning pointer field:
struct Node {
v int
next ^Node?
}
fn main() int {
mut n: ^Node = ^Node { v: 1, next: Some(^Node { v: 2, next: None }) }
n.next = None // the second node's block goes back here
return n.v
}&xs[i] and the counted-element rule
&xs[i] borrows the element, a &T, or gives its address where a ^T is
asked, and like xs[i] stops the program with a trap when i is out of
range. &xs.get(i) answers ^T? —
the element’s address, or nothing if the index missed:
fn main() int {
mut xs: []int = [10, 20, 30]
return match &xs.get(1) { Some(p) => p.^ None => 0 }
}The element may own things, too. A collection’s length lives in the value, so the block would have nothing to say when a reference outlived every value holding it — it keeps a count of its own for exactly that, written when the reference is taken:
fn main() int {
mut xs: []string = ["a", "bb"]
q := &xs.get(0)
return match q { Some(p) => p.^.len() None => 0 }
}What is refused is the mutation, not the reference — ATOLL1070. Taking one
into an element that owes a destructor is ordinary:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
fn main() int {
mut xs: []Tag
xs.push(Tag { k: 1 })
return match &xs.get(0) { Some(p) => p.^.k None => 0 }
}Growing the collection while that reference is live is not:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
fn main() int {
mut xs: []Tag
xs.push(Tag { k: 1 })
p := &xs.get(0)
xs.push(Tag { k: 2 })
return match p { Some(t) => t.^.k None => 0 } // `p` is read past the push
}The reference borrows the list’s block, and the push would change that block
while the reference is still to be read. Nothing copies the block behind the
program’s back to make room for both: a write finds its block unique, or it is
refused while a borrow of it is still to be used. .clone() is how to ask for
a second list.
Another reference into it is not a mutation. No other list shares the block of a
list whose elements owe a destructor, so a second &xs[j] copies nothing: both
references name the list’s own block, a write through either lands in the list,
and each destructor runs once:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
fn main() int {
mut xs: []Tag
xs.push(Tag { k: 1 })
xs.push(Tag { k: 2 })
p := &xs.get(0)
q := &xs.get(1)
match p { Some(mut t) => { t.^.k = 10 } None => {} }
second := match q { Some(t) => t.^.k None => 0 }
first := match &xs.get(0) { Some(t) => t.^.k None => 0 }
return first + second // 10 and 2
}A reference is in force only where something that carries it is used later on that path, as Polonius has it: past its last use it holds nothing, and the refusal names the later use. A call is judged by what its callee does, which the compiler works out from the callee’s body: which parameters a returned reference comes from, and which fields it reads and writes through each one it borrows. So the repair is to finish with the reference before the change, and a narrower scope is one way to write that:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
fn main() int {
mut xs: []Tag
xs.push(Tag { k: 1 })
mut seen: int = 0
{
p := &xs.get(0)
seen = match p { Some(q) => q.^.k None => 0 }
}
xs.push(Tag { k: 2 })
return seen + xs.len().to_int()
}Without the braces, the same program is taken, since p is not read past the
push:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
fn main() int {
mut xs: []Tag
xs.push(Tag { k: 1 })
p := &xs.get(0)
seen := match p { Some(q) => q.^.k None => 0 } // the last use of `p`
xs.push(Tag { k: 2 })
return seen + xs.len().to_int()
}planned marks a design not built yet. Today’s compiler holds a reference to
the end of the block that binds it, and refuses this program (ATOLL1070).
Keeping the element instead (return xs[i], ys.push(xs[i]), a mut name
bound to it: each takes a count of what xs[i] borrows) is not open to a
Tag: a type that owes a destructor and carries no count has no second holder
to give, so a kept xs[i] of one is ATOLL1089. Reading it where it sits is
open: xs[i].k reads the field in place and keeps nothing, so nothing is
copied out (the new compiler takes it; today’s still refuses it as a copy,
ATOLL1089). The reference is how to hold on to it across statements; pop()
and take_at(i) take it out. For an element that is reference counted — a
string, a list — xs[i] is an ordinary read and ties nothing down.
A mutation is anything that takes the collection mut — push, pop, clear,
xs[i] = v, assigning over it, or binding it to a second mut name. A for
loop over the elements lends each one where it sits, and is not one of these
references: the walk borrows the list, a change it goes on past is refused
(ATOLL3105, see Loops),
and so is a use of a lent element past a change (ATOLL1097). A lent Tag is read in
place; giving one away is a copy, ATOLL1089, and for t in xs.drain() hands
them over instead — see
Lists.
A generic
fn head[T](xs: []T) that only indexes keeps working too; one that indexes and
mutates is refused for every T, because nothing can say whether T owes a
destructor and there is no affinity bound to say it with.
Writing through a reference
A write through a reference is a write to what it was taken from, so it needs
mut there — the rule a field assignment follows. Some(mut q) makes the
name q writable; it does not make xs writable:
fn main() int {
xs := [1, 2, 3]
match &xs.get(0) { Some(mut q) => { q.^ = 9 } None => {} }
return xs.get(0) ?? 0
}The rule follows the reference out of a call. A function that hands back a reference into a parameter it borrows hands back a read-only one: reading through it is fine, writing through it is the same refusal.
fn first(xs &[]int) ^int? {
return &xs.get(0)
}
fn main() int {
ys := [1, 2, 3]
match first(ys) { Some(mut q) => { q.^ = 9 } None => {} }
return ys.get(0) ?? 0
}The name holding a reference is a slot of its own. Handing &mut q to a &mut
parameter whose function only assigns that slot (p.^ = None) gives q
another reference and writes nothing through the one it held, so it needs
mut on q alone; a function that writes past the slot, through the
reference it holds, is the same refusal.
From a mut binding the write lands in that list alone. snapshot := b.items.clone()
is a list of its own, so the write reaches b.items and not snapshot:
struct B { items []int }
fn main() int {
mut b := B { items: [1, 2, 3] }
snapshot := b.items.clone()
match &b.items.get(0) { Some(mut q) => { q.^ = 9 } None => {} }
return (snapshot.get(0) ?? 0) * 100 + (b.items.get(0) ?? 0)
}Handing the list on while a reference into it that may be written through is live is refused: a binding, an assignment, a struct literal’s field or a list literal’s element naming it, or a struct holding it. There is one owner, and the reference is into what it holds:
struct B { items []int }
fn main() int {
mut b := B { items: [1, 2, 3] }
p := &b.items.get(0)
snapshot := b.items
match p { Some(mut q) => { q.^ = 9 } None => {} }
return (snapshot.get(0) ?? 0) * 100 + (b.items.get(0) ?? 0)
}Hand the list on before taking the reference, as above, or after the reference’s last use, when a clone holds the write that came first:
struct B { items []int }
fn main() int {
mut b := B { items: [1, 2, 3] }
p := &b.items.get(0)
match p { Some(mut q) => { q.^ = 9 } None => {} }
snapshot := b.items.clone()
return (snapshot.get(0) ?? 0) * 100 + (b.items.get(0) ?? 0)
}Handing the list to a &mut parameter is not a hand-off: the function works on
the same list.
The block is the unit, and a reference pins all of it
There is one count per block. A reference to a single element therefore keeps the whole buffer alive — there is no sub-block count.
A reference borrows what it was taken from, so a change to the container —
growing it, xs[i] = v, a push within capacity — ends the borrow. The
reference may not be used past that point, to read or to write (ATOLL1097):
fn main() int {
mut xs := ["a", "bb", "ccc"]
p := &xs[1]
xs.push("dddd") // the borrow ends here
return p.len() // refused: a use past the change
}What is refused is the use, not the reference. One you have finished with costs nothing, and two references that only read do not conflict:
fn main() int {
mut xs := ["a", "bb", "ccc"]
a := &xs[1]
b := &xs[2]
seen := a.len() * 10 + b.len() // the last use of both
xs.push("dddd") // nothing is borrowed here
return seen
}A number read through & where a value is asked is no reference at all:
x: int = &xs[1] copies the element and borrows nothing, so the list may
change while x is still to be read, where r := &xs[1] is the reference and
the change is refused. An element that owes is not read through: s: string = &names[0] is refused (ATOLL2002), and names[0].clone() is the value of its
own (Pointers).
fn main() int {
mut xs := [10, 20, 30]
x: int = &xs[1] // a copy: nothing is borrowed
xs.push(40)
return x
}A reference lent to a call is used when the call runs, after its last
argument, so a later argument that changes the list is refused too, whatever
the element’s type. front-fail= marks a refusal the new compiler gives; today’s
compiler lends a copy of a number’s element and takes it:
fn read(t &int, n int) int { return n }
fn main() int {
mut xs := [1, 2, 3]
return read(&xs[0], {
xs[0] = 5 // refused: the call reads `&xs[0]` after this
1
})
}The rule follows the reference through the names, fields, lists and closures that hold it, and through a call: one handed the list where it may change it, or handed the reference where it may write through it, counts. A branch counts if either arm changes the list, and a loop’s change reaches the next turn’s use. So finish with a reference into a container before the container changes, and take a fresh one after. Lists says the same thing about views.
A reference into static storage
&CONST is a reference into storage no activation owns, so it outlives every
frame and is never released:
const BASE: int = 7
fn look(p &int) int { return p }
fn main() int {
return look(&BASE)
}A reference read out of an owning field
A pointer field hands its block back when the container is released, so a
^C read out of one is a reference to a block the container holds the
count on. Handing it back out is the first method anybody writes on a node
type, and it works:
struct C { v int }
struct O { c ^C }
fn get(o &O) ^C { return o.c }
fn main() int {
o: ^O = ^O { c: ^C { v: 7 } }
return get(o).v
}It works when the container is one the caller lends you, as above, and it works when the container is the callee’s own:
struct C { v int }
struct O { c ^C }
fn get() ^C {
o: ^O = ^O { c: ^C { v: 7 } }
return o.c
}
fn main() int {
return get().v
}The two are not the same mechanism, and the difference is worth knowing because it is the difference between free and not.
A lent container costs nothing. The caller holds o live across the
whole call, so the block o.c names is still held when the reference gets
home. The compiler records whose container the reference came from and
the reference owes no count at all.
A container the callee owns pays a retain. o is released at the end
of get, so a reference that leaves has to be an owner in its own right:
the read takes a count, and whoever receives it gives that count back. The
same thing a collection does — xs[0] kept past its source takes a count,
and &xs[0] is the reference that does not.
You do not write either one. The read is a borrow when it stays inside the function and an owner when it leaves — returned, stored into a block, put in a closure, or handed to a parameter that may keep it:
struct C { v int }
struct O { c ^C }
fn get(o ^O) ^C { return o.c }
fn main() int {
return get(^O { c: ^C { v: 7 } }).v
}That is what makes a recursive structure walkable:
struct N { v int, next ^N? }
fn total(xs ^N?) int {
match xs {
Some(n) => { return n.v + total(n.next) }
None => { return 0 }
}
}
fn main() int {
return total(^N { v: 7, next: ^N { v: 5, next: None } })
}total(n.next) hands a member to a parameter that owns it, so the read
retains and total releases — which is why the list can be walked one
link at a time without the caller’s node dying underneath it.
An owner holds its own type’s block
A ^T that owns what it holds — a field, an element, a parameter that takes
its argument over — gives it back as a T. A reference into a block of
another type would be given back the wrong shape, and whatever else that block
holds would never come back, so it is refused where it enters the owner:
struct N { v int, next ^N? }
struct O { pad []int, inner N }
fn mk() ^N {
o := ^O { pad: [1, 2, 3], inner: N { v: 40, next: None } }
return ^N { v: 1, next: &o.inner }
}
fn main() int {
return match mk().next { Some(m) => m.v None => 0 }
}A borrowing position takes it (p &T), and so does an owner of a block that
holds nothing a release walks: &ys[2] of a []int kept in a []^int comes
back whole either way.
Read next
- Pointers — the syntax,
^T?,&T, and the diagnostics table. - Destruction — when the block a reference holds is given back.
- Cycles — what happens when two blocks point at each other.