Pointer
Every value lives somewhere in memory, and that place has an address: a number that says where it is. A pointer is a value that holds such an address. With one, a part of the program can reach a value that lives somewhere else, read it and — when it is allowed to — change it.
You have met a close relative already: the reference, &T and &var T, from Reference. A pointer does the same job with more freedom and fewer checks. The whole of this part is built on that freedom, so this first lesson takes it slowly.
Taking an address and reaching through it
Two operators do all the work. @score takes the address of score, and *pointer reaches the value at an address:
var score: int = 10;
// Two pointers to one variable. Neither is a copy of `score`; both lead back to it.
let reader: *int = @score;
let writer: *var int = @score;
// Safety: `writer` holds the address of `score`, which is alive for all of `Main`.
unsafe { *writer = 25; }
Neither pointer holds a copy of 10. Both hold the address of score, so after *writer = 25 the variable itself says 25, and reading *reader says 25 too.
flowchart LR
reader["`reader: *int`"] -- "reads" --> score[("`score: int`<br/>`25`")]
writer["`writer: *var int`"] -- "reads and writes" --> score| Operator | Read it as | Gives |
|---|---|---|
@value | "the address of value" | a pointer |
*pointer | "the value at pointer" | the value itself, to read or to assign |
Reaching through a pointer is unsafe
Taking, copying and comparing addresses is safe. Reaching through one is not something the compiler can check — it cannot prove that the address still leads to a live value of the right type — so every read or write through a pointer sits in an unsafe { … } block. The block is your promise that the address is good, and a // Safety: comment above it says why:
// Safety: `reader` holds the address of `score` too.
PrintLine("read via pointer {}", unsafe { *reader });
An unsafe block can also be an expression, as here: its value is the value of what is inside. Keep each block as small as the one reach it covers, so the comment above it has only one thing to justify.
*T reads, *var T writes
Pointers split the same way bindings do. The var after the * describes the value pointed at — the pointee — not the pointer:
| Type | Through it you may | Like a binding made with |
|---|---|---|
*int | read *p | let |
*var int | read and write *p | var |
The split follows the original binding, too. The address of a let binding is always a read-only *int, so a pointer can never be used to change something that was declared unchangeable:
let limit: int = 100;
let limitPointer: *int = @limit;
// Safety: `limitPointer` holds the address of `limit`, which is alive.
PrintLine("limit is {}", unsafe { *limitPointer });
Asking for a *var int there is an error; the exact message is under Common mistakes below.
Fields through a pointer
To reach a field through a pointer, use a plain .. There is no need to write * first — but it is still a reach through the pointer, so it needs unsafe too:
var point = Point { x: 1, y: 2 };
let cursor: *var Point = @point;
// Safety: `cursor` holds the address of `point`, which is alive.
unsafe { cursor.x = 7; }
The write lands in point itself, which then prints as (7, 2).
null, the pointer to nowhere
Unlike a reference, a pointer can be stored, compared and set to null, which means "no address at all":
var target: *int = null;
PrintLine("target is null {}", target == null);
target = @score;
if target != null {
// Safety: `target` is not null, checked above, and holds the address of `score`.
PrintLine("target now reads {}", unsafe { *target });
}
Comparing with == and != is always safe. Reaching through null with * is not, and inside unsafe the compiler will not stop you: the program simply crashes when it gets there. Check before you reach — the check is what the // Safety: comment points to.
Two pointers are equal when they hold the same address. That is why the last line prints true — target and reader both lead to score.
Reference &T | Pointer *T | |
|---|---|---|
| Checked by the compiler | yes — it is always valid | no |
Can be null | no | yes |
| Can be stored in a field or returned | no | yes |
| Reached with | the name alone | *p, or p.field, inside unsafe |
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// A pointer is an address: a plain value that says where another value lives. `@score` takes
// the address of `score`, and `*pointer` reaches the value at that address, to read it or to
// write it.
//
// Pointers split the same way bindings do. A `*int` may only read what it points at; a
// `*var int` may also write. And the address of a `let` binding is always a read-only `*int`,
// so a pointer can never be used to change something declared unchangeable.
//
// A reference (`&T`, from the Types part) also reaches another value, but the compiler checks
// that it stays valid. A pointer is not checked: it can be stored, compared, and set to `null`,
// which means "no address at all". The rest of this part is built on that freedom, and on the
// care it asks for.
//
// Taking, copying and comparing addresses is safe. Reaching through one is not something the
// compiler can check, so every read or write through a pointer sits in an `unsafe { ... }`
// block, with a `// Safety:` comment above it saying why the address is good.
import Io::PrintLine;
struct Point {
x: int;
y: int;
}
func Main() -> int {
var score: int = 10;
// Two pointers to one variable. Neither is a copy of `score`; both lead back to it.
let reader: *int = @score;
let writer: *var int = @score;
// Safety: `writer` holds the address of `score`, which is alive for all of `Main`.
unsafe { *writer = 25; }
PrintLine("score is now {}", score);
// Safety: `reader` holds the address of `score` too.
PrintLine("read via pointer {}", unsafe { *reader });
// The address of a `let` binding is read-only. Asking for `*var int` here is an error:
// "'@limit' yields a read-only '*T'; declare 'limit' with 'var' for a '*var T'".
let limit: int = 100;
let limitPointer: *int = @limit;
// Safety: `limitPointer` holds the address of `limit`, which is alive.
PrintLine("limit is {}", unsafe { *limitPointer });
// A field is reached through a pointer with a plain `.`, without writing `*` first.
var point = Point { x: 1, y: 2 };
let cursor: *var Point = @point;
// Safety: `cursor` holds the address of `point`, which is alive.
unsafe { cursor.x = 7; }
PrintLine("point is ({}, {})", point.x, point.y);
// `null` is the pointer that points nowhere. Comparing with `==` is safe; reaching through
// it with `*` is not, and inside `unsafe` the compiler will not stop you. Check before you
// reach.
var target: *int = null;
PrintLine("target is null {}", target == null);
target = @score;
if target != null {
// Safety: `target` is not null, checked above, and holds the address of `score`.
PrintLine("target now reads {}", unsafe { *target });
}
// Two pointers are equal when they hold the same address.
PrintLine("same address {}", target == reader);
return 0;
}
Run it
cd Examples/Memory/Pointer
rux run
score is now 25
read via pointer 25
limit is 100
point is (7, 2)
target is null true
target now reads 25
same address true
Common mistakes
Try it yourself
- Add a second variable,
var bonus: int = 5;, pointtargetat it, and check thattarget == readernow printsfalse. - Write
func Swap(a: *var int, b: *var int)that exchanges two values inside oneunsafeblock, with a// Safety:comment saying what the caller must promise, and call it asSwap(@first, @second). - A pointer is a value, so it has an address too. Make
var p: *var int = @score;andlet pp: **var int = @p;, then writeunsafe { **pp = 42; }and printscore.
Learn more
- Pointers, Pointer types and The
nullpointer in the Rux Reference - Reference and Mutable reference — the checked relatives of
*Tand*var T - Out parameter — the next lesson, where a function writes through a pointer it was given
Overview
Pointers, raw memory and allocators: reach values by address, ask for memory while the program runs, and choose where it comes from — from Alloc and Free to Box, Rc, Arena, FixedBuffer and Pool.
15.2 Out parameter
Return an answer through a &var T out-parameter, and see why returning an optional T? is usually the better choice.