Guides · 09

Pointers and memory

Vyi passes values by copy: assigning a value, passing it to a function, and returning it all copy it. A pointer is how you share a value instead of copying it. Vyi has no garbage collector and no hidden heap. Nothing is allocated unless you call an allocator, so memory that has to outlive the current function is memory you ask for.

Here is what the compiler checks about pointers, and what it leaves to you:

  • No null. A pointer always points at something. "Maybe a pointer" is an optional, ?*mut T, and you have to check it before you use it. The one exception is *c_ptr T, the C pointer, which exists for calling C and may be null (guide 15).
  • Write permission is part of the type. Every pointer type says whether you may write through it: *mut T or *con T.
  • A pointer into a function's storage never outlives it. A pointer to a local binding can't be returned, and it can't be kept anywhere that lives longer than the binding.
  • Memory from an allocator is yours to manage. Once you free memory, or reset the arena it came from, the pointers into it are dead, and the compiler doesn't stop you from using them.

This guide covers the pointer types, then fixed arrays and array pointers, then allocators. It ends with how long a pointer stays valid: the checks, the lifetime annotations a function's signature can carry, and the values that hold pointers.

Pointers: *mut T and *con T

&x takes the address of x, and *p reads or writes what p points at. The pointer you get follows the binding: & of a mut binding gives a *mut T, which you may write through, and & of a con binding gives a *con T, which you may only read through:

Vyi
import { println } from "@fmt"

fn addPoints(score: *mut i32, points: i32) {
    *score += points
}

fn show(score: *con i32) {
    println(*score)
}

fn main() !u8 {
    mut score = 10
    addPoints(&score, 5)
    show(&score)   // prints 15
    return Ok(0)
}

show takes a *con i32, and &score is a *mut i32. A *mut pointer is accepted where a *con is expected, because reading through a pointer you could also write through loses nothing. The other direction is an error:

Vyi · does not compile
fn main() !u8 {
    mut level = 3
    con view: *con i32 = &level
    con edit: *mut i32 = view   // error: this value has type *con i32, but the binding is declared *mut i32
    return Ok(0)
}

Every pointer type states its write permission. *T alone is not a type:

Vyi · does not compile
fn read(p: *i32) i32 {   // error: pointer type needs
    return *p
}

Writing through a *con is an error, at any depth and across function calls, because the permission travels with the pointer's type:

Vyi · does not compile
con limit: i32 = 42

fn main() !u8 {
    con p = &limit
    *p = 99   // error: cannot assign through a pointer
    return Ok(0)
}

The binding and the pointer are separate

A binding's con or mut says whether the name can be given a new value. A pointer's *con or *mut says whether you can write to what it points at. The two don't affect each other. A con binding that holds a *mut pointer can write through it; it can't be pointed somewhere else:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut hits = 5
    con p: *mut i32 = &hits
    *p = 6
    println(hits)   // prints 6
    return Ok(0)
}

Writing p = &other here is an error, because p is con. The same goes the other way: a *con pointer in a mut binding can be pointed elsewhere, but nothing can be written through it.

Once you go through a pointer, only the pointer's type counts. With p: *mut Point, p.x can be assigned, and &p.x is a *mut i32, even when p itself is a con binding or a parameter.

Maybe a pointer: ?*mut T

A pointer can't be null, so "no pointer yet" is an optional, like any other missing value (guide 07). To get at the pointer you have to check it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut score = 10
    mut target: ?*mut i32 = None
    target = Some(&score)
    match target {
        Some(p): { *p = 20 },
        None: {},
    }
    println(score)   // prints 20
    return Ok(0)
}

The Some arm keeps its braces because its body is an assignment, which is a statement, not an expression.

Fields, methods, and pointers to pointers

Reaching through a pointer dereferences it for you, one level:

  • Field access: p.y means (*p).y.
  • Method calls: p.m() calls m on *p.
  • Patterns: match p and con Point{ x, y } = p look at *p (see a subject behind a pointer).
Vyi
import { println } from "@fmt"

struct Player { name: [*con]u8, score: i32 }

fn main() !u8 {
    mut player = Player{ name: "ada", score: 10 }
    con p = &player
    p.score = 25
    println(player.score)   // prints 25
    return Ok(0)
}

You can also take the address of a field or an element (&player.score, &scores[i]), and point at a pointer. Only one level is dereferenced for you; each further level needs an explicit *:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut score = 10
    con p = &score
    con pp = &p
    **pp = 30
    println(score)   // prints 30
    return Ok(0)
}

For the same reason, if pp points at a pointer to a Player, pp.score is an error: one level down from pp is still a pointer, and a pointer has no fields. Write (*pp).score.

A method's receiver uses the same write permission. A method declared fn (c: *mut Counter) bump() can be called only on a mut binding or through a *mut pointer. One declared fn (c: *con Counter) peek() can be called on any Counter, without copying it. A method that takes Counter by value, called through a pointer, gets a copy of what the pointer points at:

Vyi
import { println } from "@fmt"

struct Counter { hits: i32 }

fn (c: *mut Counter) bump() { c.hits += 1 }
fn (c: *con Counter) peek() i32 { return c.hits }

fn main() !u8 {
    mut clicks = Counter{ hits: 0 }
    clicks.bump()
    println(clicks.peek())   // prints 1

    con fixed = Counter{ hits: 5 }
    println(fixed.peek())   // prints 5
    return Ok(0)
}

fixed.bump() would be an error, because fixed is con. The rules for choosing between methods that share a name are in methods and dispatch.

Comparing pointers

Pointers support == and !=, which test whether two pointers hold the same address. There is no pointer arithmetic. To walk through memory element by element, use an array pointer, covered below:

Vyi · does not compile
fn main() !u8 {
    mut x = 1
    con p = &x
    con q = p + 1   // error: operator `+` is not allowed
    return Ok(0)
}

& needs a place

& needs a place to point at: a binding, a field or element of one, or a dereference. A value that isn't stored anywhere, such as a call's result, a literal, or the result of a + b, has no address, so &makePoint() is an error. Bind the value to a name first, then take its address:

Vyi · does not compile
struct Point { x: i32, y: i32 }

fn makePoint() Point { return Point{ x: 1, y: 2 } }

fn main() !u8 {
    con p = &makePoint()   // error: cannot take the address
    return Ok(0)
}

The left side of = follows the same rule. makePoint().x = 1 is an error, because the write would land in a value that nothing can read afterwards.

Fixed arrays: [N]T

[N]T is an array of exactly N elements of type T. The length is part of the type, so [3]i32 and [4]i32 are different types. A literal names the type, then lists the elements. Empty brackets fill the array with zeros, and are the one way to get zeros without writing them out (guide 03):

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con primes = [4]i32[2, 3, 5, 7]
    mut flags = [4]u8[]   // four zero bytes
    flags[2] = 1
    println(primes[3])   // prints 7
    println(flags[2])    // prints 1
    return Ok(0)
}

Indexing a fixed array is always checked. When the index is a known value, the check happens when you compile: primes[9] on a [4]i32 is an error. When the index is computed while the program runs, an index outside 0 to N - 1 panics with array index out of bounds, for reads and writes alike.

.len is the array's length N, as an i32. Because the length is part of the type, .len is a known value, so you can use it anywhere a known value is needed, such as the length of another array:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con prices = [4]i32[120, 80, 45, 300]
    con discounts = [prices.len]i32[]
    println(discounts.len)   // prints 4
    return Ok(0)
}

In a loop such as for i in 0..prices.len { total += prices[i] }, the index check is free. When the index is exactly the loop variable of a for over a range, both ends of the range are known values, and the range stays inside the array, the compiler has already proved every index in range and skips the check. Anything else keeps its check: an index computed from the loop variable (prices[i + 1]), a range whose end is only known when the program runs, or a range that reaches past the array.

An array is a value. Assigning it copies every element, and the copy is independent:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut original = [3]i32[1, 2, 3]
    mut copy = original
    copy[0] = 50
    println(original[0])   // prints 1
    println(copy[0])       // prints 50
    return Ok(0)
}

Passing an array or a struct to a function works the same way. The parameter is read-only, and writing to it is an error. To change it, copy it into a mut binding of your own:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn shifted(p: Point, dx: i32) Point {
    mut moved = p
    moved.x += dx
    return moved
}

fn main() !u8 {
    con start = Point{ x: 7, y: 8 }
    con next = shifted(start, 3)
    println(start.x)   // prints 7
    println(next.x)    // prints 10
    return Ok(0)
}

When you want a function to change your array instead of a copy, pass a pointer to it. Indexing through a pointer to a fixed array dereferences it for you, the same way field access does: with p: *mut [4]i32, p[i] means (*p)[i]:

Vyi
import { println } from "@fmt"

fn clearFirst(scores: *mut [4]i32) {
    scores[0] = 0
}

fn main() !u8 {
    mut scores = [4]i32[9, 8, 7, 6]
    clearFirst(&scores)
    println(scores[0])   // prints 0
    return Ok(0)
}

Array pointers: [*con]T and [*mut]T

An array pointer is a pointer and a length carried together in one value. Other languages call this a slice. It views zero or more Ts stored somewhere else. It can't be null, and every index is checked against its length. You'll use it more than any other pointer type: a string literal is a [*con]u8, and allocators hand out [*mut]Ts. As with single pointers, [*mut]T lets you write the elements and [*con]T doesn't.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con word = "hello"
    println(word.len)   // prints 5
    println(word[0])    // prints 104
    return Ok(0)
}

The length lives in the value, not in the type. An element is a byte, so it prints as a number: 104 is the code for h.

An index is a position from the start, and nothing counts from the end: the last element is word[word.len - 1]. An index outside 0 to len - 1 panics with array index out of bounds (guide 08), and a negative index that is a known value, such as word[-1], is a compile error. There is no unchecked indexing. .ptr gives the bare address, as a C pointer, for when you call C.

Slicing

Indexing with a range gives another array pointer, over part of the same storage. Slicing never copies:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con line = "hello world"
    println(line[..5])     // prints hello
    println(line[6..])     // prints world
    println(line[3..8])    // prints lo wo
    println(line[...4])    // prints hello
    return Ok(0)
}

lo..hi includes lo and stops before hi, as ranges do everywhere in Vyi. lo...hi includes hi too. Leave out lo to start at the beginning, or hi to run to the end; line[..] is the whole thing, and line[line.len - 3..] is the last three bytes. A bound outside 0 <= lo <= hi <= len panics, and a negative bound that is a known value is a compile error.

A pointer to a fixed array can be sliced the same way. Through a *mut [4]i32, p[1..3] is a [*mut]i32 over two of the array's elements.

Converting between [N]T and array pointers

A conversion is written as the target type applied like a function. The one you'll use most turns a pointer to a fixed array into an array pointer over the same storage, taking the length from the [N] in the type:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut bytes = [4]u8[1, 2, 3, 4]
    con view = [*mut]u8(&bytes)
    view[1] = 20   // writes into bytes
    println(bytes[1])   // prints 20
    println(view.len)   // prints 4
    return Ok(0)
}

This is how an array on the stack gets passed to anything that takes a [*mut]T, such as the FixedBufferAllocator below.

Converting to a fixed array goes the other way and copies: [4]u8(bytes) copies four elements out of an array pointer into a new [4]u8 of your own. *[4]u8(bytes) doesn't copy: it gives a pointer to a fixed array over the same storage, with the length moved from the value into the type. ([*mut]u8(p) turns that pointer back into an array pointer.)

Vyi
import { systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    con bytes = try systemAllocator.alloc(4, 1)
    defer systemAllocator.free(bytes)
    bytes[0] = 7

    con copy = [4]u8(bytes)   // a new array
    con same = *[4]u8(bytes)  // the same storage
    bytes[0] = 100
    println(copy[0])   // prints 7
    println(same[0])   // prints 100
    return Ok(0)
}

To sum up: converting to a pointer shape views the same storage, and converting to a fixed array copies.

Allocators

So far everything has lived in a function's storage or in the program's own data. Memory that has to outlive a function, or whose size you only learn while the program runs, comes from an allocator. An allocator is a value you pass around. A function that allocates takes an allocator as a parameter, so you can see from its signature that it allocates.

The @mem package declares the Allocator interface. Its alloc method returns OutOfMemory![*mut]u8: exactly the bytes you asked for, or an error. It never returns null and never hands you an empty buffer in place of an error. You deal with the failure with try or catch, like any error (guide 07):

Vyi
import { Allocator, OutOfMemory } from "@mem"

fn scratch(alloc: Allocator) OutOfMemory![*mut]u8 {
    return alloc.alloc(64, 1)
}

alloc(size, align) takes the number of bytes and the alignment the memory needs. free(buf) gives memory back.

The allocator for general use is systemAllocator, the platform heap:

Vyi
import { systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    con buf = try systemAllocator.alloc(64, 1)
    defer systemAllocator.free(buf)
    println(buf.len)   // prints 64
    return Ok(0)
}

defer frees the buffer on every way out of main (guide 08).

Typed allocation: new

Raw bytes are rarely what you want. new allocates storage for a type and works out the size and alignment for you. new(T) gives a *mut T for one value, and new(T, count) gives a [*mut]T of count elements. Both return OutOfMemory on failure. delete gives memory from new back.

Vyi
import { systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    con scores = try systemAllocator.new(i32, 3)
    defer systemAllocator.delete(scores)
    println(scores.len)   // prints 3

    con best = try systemAllocator.new(i32)
    defer systemAllocator.delete(best)
    *best = 90
    println(*best)   // prints 90
    return Ok(0)
}

sizeof T and alignof T give a type's size and alignment, if you need them yourself.

Allocator is an ordinary interface (guide 12), so code written against it works with every allocator, including ones you write. An allocator implements alloc and free, and gets new and delete from the interface.

Choosing an allocator

@mem provides these allocators:

  • systemAllocator: the platform heap. Frees each allocation on its own.
  • FixedBufferAllocator: hands out pieces of a buffer you provide, often an array on the stack. It never touches the heap. free does nothing, and reset() makes the whole buffer available again. When the buffer is full, allocation fails with OutOfMemory.
  • ArenaAllocator: takes memory from a parent allocator in chunks, 4096 bytes unless you pass another size to ArenaAllocator.new, and hands it out piece by piece. free does nothing. reset() reclaims everything at once and keeps the chunks for reuse; deinit() gives the chunks back to the parent. It suits work that happens in phases: build, use, throw everything away.
  • PageAllocator: takes whole pages from the operating system. It's what other allocators are built on, not one to allocate single values from.
  • TestingAllocator: wraps another allocator and counts the allocations that haven't been freed, so a test can check that nothing leaked.

A FixedBufferAllocator over a stack array:

Vyi
import { Allocator, FixedBufferAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut buf = [64]u8[]
    mut fixed = FixedBufferAllocator.new([*mut]u8(&buf))
    con alloc: Allocator = &fixed

    con nums = try alloc.new(i32, 4)
    nums[0] = 42
    println(nums[0])   // prints 42
    return Ok(0)
}

con alloc: Allocator = &fixed turns a pointer to the allocator into an Allocator interface value, which is what a function that takes any allocator expects.

Allocators wrap each other. Each one takes memory from a parent through the same interface, so you can put a leak check or an arena over any allocator, and neither side needs to know:

Vyi
import { Allocator, TestingAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut counted = TestingAllocator.new(systemAllocator)
    con alloc: Allocator = &counted
    con buf = try alloc.alloc(16, 1)
    println(counted.liveAllocations())   // prints 1
    alloc.free(buf)
    println(counted.liveAllocations())   // prints 0
    return Ok(0)
}

An allocator has no resize: it only allocates and frees. To grow a buffer, allocate a bigger one, copy, and free the old one. Buffer and Vec do that for you (guide 10).

Memory you free stays your responsibility

The compiler doesn't track when allocator memory dies. Using memory after you free it, or using memory from an arena after reset(), compiles, and reads whatever that memory holds at the time:

Vyi
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    defer arena.deinit()
    con first = try arena.new(u8, 4)
    first[0] = 7
    arena.reset()
    con second = try arena.new(u8, 4)
    second[0] = 9
    println(first[0])   // prints 9
    return Ok(0)
}

After reset(), first is dead. The arena reuses its memory from the start, so second lands in the same place and first[0] reads second's byte. When you free or reset, make sure nothing still uses that memory.

How long a pointer stays valid

A pointer is valid while the storage it points at exists. For storage in a function, the compiler checks this for you. This section shows the checks. The sections after it show how a function's signature states lifetimes, and how the values that hold pointers follow the same rules.

Returning a pointer

A function's own bindings end when it returns, so returning a pointer to one is an error:

Vyi · does not compile
fn dangling() *mut i32 {
    mut local = 42
    return &local   // error: frame-bound pointer
}

The message suggests the ways out: take the memory from an allocator, or return the value itself instead of a pointer to it.

A pointer lives as long as its block

Inside a function, the same check works block by block. Storage belongs to the block that declares it and ends when that block ends. These are blocks: a function body, each branch of an if or else, each arm of a switch or match, a defer body, a bare { }, and a loop body, which ends at the end of every iteration. A pointer can't be stored anywhere that lives longer than what it points at, so a pointer to a block's binding can't be stored in a binding declared outside that block:

Vyi · does not compile
fn main() !u8 {
    mut a = 0
    mut ps = [3]*mut i32[&a, &a, &a]
    for i in 0..3 {
        mut y = i
        ps[i] = &y   // error: this *mut i32 points into
    }
    return Ok(u8(*ps[0]))
}

The full message reads: this *mut i32 points into storage that ends with this loop iteration, but ps outlives it. Without the check, every element of ps would point at the one place the loop reuses for y on each iteration. Declare what the pointers point at where it lives long enough, here outside the loop:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut ys = [3]i32[0, 0, 0]
    mut ps = [3]*mut i32[&ys[0], &ys[0], &ys[0]]
    for i in 0..3 {
        ps[i] = &ys[i]
    }
    *ps[2] = 20
    println(ys[2])   // prints 20
    return Ok(0)
}

The same holds for the value of an if, switch, match or { } used as an expression: the value outlives the block, so it can't point into it. These are always fine: passing a pointer into a call, keeping it in a binding of the same block or of a block inside it, and pointing from an inner block to storage of an outer one.

A binding is judged by everything ever stored into it. Once h = &x appears anywhere in a function, h counts as short-lived as x everywhere in that function, even before the line that stores &x.

Stores through a pointer are checked too

Writing a pointer through another pointer, as in *p = &x, p.next = &x, or p[i] = &x, is checked against the storage being written into. Here p points at head, which outlives tail:

Vyi · does not compile
struct Node { value: i32, next: ?*mut Node }

fn main() !u8 {
    mut head = Node{ value: 1, next: None }
    con p = &head
    if head.value > 0 {
        mut tail = Node{ value: 2, next: None }
        p.next = Some(&tail)   // error: this Optional
    }
    return Ok(0)
}

The message names the type of what is stored, here Optional(*mut Node), the long spelling of ?*mut Node.

A function that stores a pointer it was given into what another parameter points at passes the requirement on to its callers (below).

What may leave a function

A pointer may be returned, or stored somewhere long-lived, when its storage outlives the function. These pointers can:

  • a pointer from an allocator (alloc or new), as long as the allocator itself outlives the function,
  • a pointer to a file-level variable, or to a known value, which the compiler stores in the program's data (a string literal's bytes are the everyday example),
  • a pointer the function received as a parameter, or one into what the parameter points at, since the caller's storage outlives the call.

A struct whose pointers all qualify may be returned too. A function that takes an allocator can hand back what it allocates:

Vyi
import { Allocator, OutOfMemory, systemAllocator } from "@mem"
import { println } from "@fmt"

fn newScore(alloc: Allocator) OutOfMemory!*mut i32 {
    con score = try alloc.new(i32)
    *score = 100
    return Ok(score)
}

fn main() !u8 {
    con score = try newScore(systemAllocator)
    defer systemAllocator.delete(score)
    println(*score)   // prints 100
    return Ok(0)
}

Memory from an allocator lives as long as the allocator. So memory from an arena declared inside a function may hold pointers to that function's bindings, but it can't be returned from the function.

Lifetime annotations

A function can return a pointer it was given, or a pointer into what it was given. The compiler reads the function's body to work out how long the result stays valid. To state it yourself, as part of the function's contract, write a lifetime annotation after the return type: an apostrophe, then the names the result is tied to in parentheses:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn main() !u8 {
    mut pt = Point{ x: 1, y: 2 }
    con x = xOf(&pt)
    *x = 10
    println(pt.x)   // prints 10
    return Ok(0)
}

Read '(p) as "valid as long as what p refers to": the point p points at, not the parameter itself. The annotation isn't part of the function's type. xOf has the same type with or without it.

Join several names with & to tie the result to all of them. The result is then valid only while every one of them is, which is what a result that can come from either of two arguments needs:

Vyi
import { println } from "@fmt"

fn larger(a: *mut i32, b: *mut i32) *mut i32 '(a & b) {
    if *a > *b { return a }
    return b
}

fn main() !u8 {
    mut low = 1
    mut high = 2
    con p = larger(&low, &high)
    println(*p)   // prints 2
    return Ok(0)
}

Checked from both sides

The body is checked against the annotation. Everything the function returns must be valid at least as long as the annotation says. Returning something tied to a parameter the annotation doesn't list is an error at that return:

Vyi · does not compile
fn second(a: *mut i32, b: *mut i32) *mut i32 '(a) {
    return b   // error: the result is declared to live as long
}

The full message adds that this value lives only as long as what b refers to. Declaring a shorter lifetime than the value really has is always accepted, because claiming less than the truth is safe.

Callers rely on the annotation. At a call, the result is tied to the arguments passed for the names the annotation lists. The compiler uses the annotation, not the body, so the body can change without changing what callers may do. Here xOf(&pt) is valid as long as pt, a binding of firstX, so firstX can't return it:

Vyi · does not compile
struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn firstX() *mut i32 {
    mut pt = Point{ x: 0, y: 0 }
    return xOf(&pt)   // error: frame-bound pointer *mut i32
}

Pass something that outlives the call, such as a parameter of the calling function, and the same result can be returned:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn leftEdge(corner: *mut Point) *mut i32 {
    return xOf(corner)   // the caller owns the point
}

fn main() !u8 {
    mut corner = Point{ x: 7, y: 0 }
    println(*leftEdge(&corner))   // prints 7
    return Ok(0)
}

"Forever" is the name of a file-level variable. No keyword means "valid forever". Name a file-level variable instead: it lives for the whole program, and so does anything tied to it:

Vyi
import { println } from "@fmt"

mut counter: i32 = 0

fn counterSlot() *mut i32 '(counter) {
    return &counter
}

fn main() !u8 {
    *counterSlot() = 5
    println(counter)   // prints 5
    return Ok(0)
}

Storing a pointer into a parameter

A function that only uses a pointer it's given, reading or writing through it or passing it to another call, puts no condition on its caller. The parameter is borrowed for the call.

A function that keeps a pointer it's given, by storing it somewhere the caller can still reach after the call, does put a condition on its caller: the pointer must stay valid at least as long as the place it's kept in. The compiler works this out from the body:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn store(s: *mut Shelf, p: *mut Point) {
    s.last = p   // keeps `p` in what `s` refers to
}

fn main() !u8 {
    mut a = Point{ x: 3, y: 4 }
    mut shelf = Shelf{ last: &a }
    mut b = Point{ x: 5, y: 6 }
    store(&shelf, &b)
    println(shelf.last.x)   // prints 5
    return Ok(0)
}

store keeps p in what s refers to, so it requires p '(s): the argument for p must be valid at least as long as what the argument for s refers to. Your editor shows a lifetime the compiler worked out where you would write it, as it does for inferred types. Every call is checked with the arguments it actually passes. b and shelf above end together, so the call is fine. A point that ends before the shelf is an error at the call:

Vyi · does not compile
struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn store(s: *mut Shelf, p: *mut Point) {
    s.last = p
}

fn main() !u8 {
    mut a = Point{ x: 3, y: 4 }
    mut shelf = Shelf{ last: &a }
    if a.x > 0 {
        mut b = Point{ x: 5, y: 6 }
        store(&shelf, &b)   // error: the argument for `p`
    }
    return Ok(u8(shelf.last.x))
}

The full message adds that store requires p '(s), inferred from its body, and that the argument points into storage that ends with this block. The requirement carries through any number of calls: a function that passes p and s on to store requires the same. A function that stores into a file-level variable requires an argument that lives forever, shown with the variable's name, as in p '(latest). Storing a pointer to one of the function's own bindings into what a parameter refers to is an error at that store, since the binding ends when the function returns.

To make the requirement part of the function's contract, write it after the parameter's type. Callers are then checked against what's written, not against the body:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn (s: *mut Shelf) put(p: *mut Point '(s)) {
    s.last = p
}

fn main() !u8 {
    mut a = Point{ x: 3, y: 4 }
    mut shelf = Shelf{ last: &a }
    mut b = Point{ x: 5, y: 6 }
    shelf.put(&b)
    println(shelf.last.x)   // prints 5
    return Ok(0)
}

The body is checked too. It may keep p only where the annotation covers, and keeping it anywhere else is an error at that store:

Vyi · does not compile
struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn put(s: *mut Shelf, other: *mut Shelf, p: *mut Point '(s)) {
    other.last = p   // error: `p` is declared to live as long as `s`
}

An annotation that asks for more than the body needs is accepted. With several names joined, p '(a & b), the argument must outlive what each of them refers to.

Values that hold pointers

A value that holds a pointer can't outlive what the pointer points at, any more than the pointer can. The same checks apply to it unchanged. Three kinds of value hold pointers: a struct with a pointer field, a closure, and an interface value.

A struct with a pointer field

In a struct, each pointer field has its own lifetime, called its slot. A struct can hold one pointer to text that lasts for the whole program and another to a local binding that ends with its function. Reading the first out of the struct isn't limited by the second:

Vyi
import { println } from "@fmt"

struct Report {
    title: [*con]u8,    // a string literal: lasts forever
    scratch: *mut i32,  // a local binding of titleOf
}

fn titleOf() [*con]u8 {
    mut count = 3
    con r = Report{ title: "totals", scratch: &count }
    return r.title
}

fn main() !u8 {
    println(titleOf())    // prints totals
    return Ok(0)
}

Returning r.title is fine. Returning r.scratch instead is an error, because count ends when titleOf returns. This holds wherever the struct is: in a binding, behind a pointer, inside another struct, or in an array.

You write nothing for this. Building the struct fills each slot from the value you give its field, and the compiler works out the rest. A slot needs a name only when a function signature has to talk about it (below). The name is an apostrophe and an identifier after the field's type:

Vyi
struct Buffer { n: i32 }

struct Parser {
    source: [*con]u8 'src,   // the slot `src`
    rest: [*con]u8 'src,     // the same slot `src`
    scratch: *mut Buffer '_, // the slot `scratch`
    log: *mut Buffer,        // the slot `log`
}

Two fields with the same slot name share one lifetime. '_ names the slot after its field. A field with no slot name still has a slot of its own, and a signature refers to it by the field's name wherever the field is visible, so a private field's slot can be named only in its own file. A slot name goes only on a field that holds a pointer.

A closure points at its instance

A closure value points at its instance, which holds the values the closure captured (guide 04). The instance lives where the closure literal is written, like any other value:

  • A closure literal that initializes a binding lives as long as that binding. So does one written inside a struct, tuple, array, or variant literal that initializes a binding, such as con b = Box{ f: () => n }.
  • Any other closure literal is temporary and ends with its statement. That covers one passed as an argument, stored into a field or an element, or returned.
  • A closure created in a loop body lives for one iteration.

Calling a closure in the scope where it's written, and passing it down into a call, are always fine. Storing it somewhere that outlives its instance is an error, exactly as for & of a binding in that block:

Vyi · does not compile
fn main() !u8 {
    mut pricing = (price: i32) i32 => price
    {
        con tax = 10
        con withTax = (price: i32) i32 => price + tax
        pricing = withTax   // error: this fn(i32) i32 points
    }
    return Ok(u8(pricing(100)))
}

A closure that captures nothing has no instance, and neither does a named function used as a value, so both are fine anywhere. To keep a closure that captures something longer than its scope, put it into an allocator (guide 04).

An interface value points at its value

An interface value (guide 12) holds a pointer to the value it was made from, so it can't outlive that value: a function can't return an interface value made from one of its own bindings. A call through an interface value requires of its arguments what the implementations of that method in your program require, as a call of store above requires p '(s). Lifetimes written on an interface method's parameters, and slots written on an interface type, are (planned).

Lifetimes in depth (advanced)

The sections above cover the annotations ordinary code needs. This one is for pointers to pointers, structs with several pointer fields, and functions that take functions which keep their arguments. You can skip it on a first read. The written lifetimes section of the memory model reference has the complete rules.

One group per pointer level

Inside the parentheses, , separates pointer levels, outermost first. pp: *mut *mut i32 '(a, b) says what pp points at lives as long as a, and what the pointer stored there points at lives as long as b. One group covers every level. A shorter list fills from the outside in, and its last group covers every deeper level. Writing more groups than the type has pointer levels is an error.

Vyi
import { println } from "@fmt"

struct Box { p: *mut i32 }

fn keepInner(a: *mut Box, b: *mut Box, pp: *mut *mut i32 '(a, b)) {
    b.p = *pp   // the inner pointer lives as long as `b`
}

fn main() !u8 {
    mut x = 4
    mut y = 5
    mut px = &x
    mut a = Box{ p: &y }
    mut b = Box{ p: &y }
    keepInner(&a, &b, &px)
    println(*b.p)   // prints 4
    return Ok(0)
}

A result's annotation with several levels is read as tied to every name it lists.

Lifetimes of struct slots

A struct with several pointer fields has a lifetime for each of them, its slots (above). The annotations so far cover a whole value at once. To state slots one by one, write the slot's name between the apostrophe and the parentheses. Several annotations can follow one type:

Vyi
import { println } from "@fmt"

struct Buffer { n: i32 }
struct Parser {
    source: [*con]u8 'src,
    scratch: *mut Buffer 'tmp,
}

fn make(text: [*con]u8, buf: *mut Buffer) Parser 'src(text) 'tmp(buf) {
    return Parser{ source: text, scratch: buf }
}

fn main() !u8 {
    mut b = Buffer{ n: 4 }
    con p = make("parse", &b)
    println(p.scratch.n)   // prints 4
    return Ok(0)
}

Inside the parentheses, a name can also be a path: '(p.src) is the slot src of p, '(p._) is every slot one layer down, and '(ws[_]) is the elements of an array pointer or a fixed array. A slot you don't write is worked out from the body, even when another slot of the same value is written. The editor shows inferred slot lifetimes. A slot no annotation can name, such as the elements of a collection or a private field of another file, is shown in ⟨ ⟩, as in v '⟨items[_]⟩(...). The reference lists every form and its errors.

A struct that holds another struct can rename the inner struct's slots. After the field's type, write the inner slot's name and then, in parentheses, the outer slot it becomes:

Vyi
struct Buffer { n: i32 }

struct Parser {
    source: [*con]u8 'src,
    scratch: *mut Buffer 'tmp,
}

struct Session {
    parser: Parser 'src('text) 'tmp('work),
    log: *mut Buffer 'log,
}

In Session, the parser's src slot is Session's slot text, and its tmp slot is the slot work. '('all), with no inner slot name before the parentheses, puts every inner slot that isn't renamed otherwise into the slot all. Inside the parentheses, a slot name always starts with an apostrophe. A plain name there is an error, because a struct declaration can't refer to a variable.

What an annotation may name

  • A name in the parentheses is a parameter, the method's receiver, or a file-level variable, or a path from one of them. On a closure literal's parameter, it can also be a binding the closure captures.
  • A parameter can't name itself, and each name is listed once.
  • Every name, and the parameter or result annotated, must hold a pointer. A binding that holds no pointer refers to nothing, so naming it is an error.
  • A receiver, an interface method's parameters, and a C function carry no annotation. Neither does a binding, a cast, a type alias, or a function type, except as described below.

A function that keeps its argument

A closure literal can annotate a parameter with a binding it captures. Such a closure keeps that argument, here in the shelf sp points at, and each direct call of it is checked against the annotation:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn main() !u8 {
    mut a = Point{ x: 3, y: 4 }
    mut shelf = Shelf{ last: &a }
    con sp = &shelf
    con keep = (p: *mut Point '(sp)) () => { sp.last = p }
    mut b = Point{ x: 8, y: 0 }
    keep(&b)
    println(shelf.last.x)   // prints 8
    return Ok(0)
}

A call through a plain fn(...) value only borrows its arguments. So a function that keeps an argument, whether the lifetime is written or worked out from its body, can't be passed where a plain function type is expected:

Vyi · does not compile
struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn each(f: fn(*mut Point) (), p: *mut Point) { f(p) }

fn fill(sp: *mut Shelf, p: *mut Point) {
    con keep = (q: *mut Point '(sp)) () => { sp.last = q }
    each(keep, p)   // error: this closure keeps its argument
}

A function type's parameter can carry a lifetime when the function type is the type of a parameter. It names another parameter of the enclosing function, or a file-level variable, and is a promise from the code that calls the function value: the argument it passes stays valid as long as what that parameter refers to.

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }
struct Shelf { last: *mut Point }

fn each(items: [*mut]Point, f: fn(*mut Point '(items)) ()) {
    mut i = 0
    for i < items.len {
        f(&items[i])   // a pointer into `items`
        i += 1
    }
}

fn fill(sp: *mut Shelf, items: [*mut]Point) {
    fn shelve(p: *mut Point) { sp.last = p }
    each(items, shelve)
}

fn main() !u8 {
    mut points = [2]Point[Point{ x: 1, y: 0 }, Point{ x: 2, y: 0 }]
    mut shelf = Shelf{ last: &points[0] }
    fill(&shelf, points[0..2])
    println(shelf.last.x)   // prints 2
    return Ok(0)
}

The promise is checked on both sides. Inside each, every call of f must pass something valid as long as what items refers to. At a call of each, the function passed for f may keep its argument anywhere that lives no longer than what items refers to. Here shelve keeps it in what sp refers to, so fill requires items '(sp) of its own callers, which main meets. Two function types that differ only in their annotations are the same type.

The instance as a value

*f, the instance of a closure f, is an ordinary immutable value. Its type is the closure's own, shared with no other closure, and its size is exactly what the closure captured. You can name the type with typeof, pass the instance by value, and call it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con n = 5
    con add = (x: i32) i32 => x + n
    type Add = typeof *add
    fn useAdd(a: Add, x: i32) i32 { return a(x) }
    con inst = *add
    println(inst(1))           // prints 6
    println(useAdd(*add, 2))   // prints 7
    return Ok(0)
}

You can write *f only where the compiler knows which closure f is: the closure literal itself, a con bound directly to one, or a nested fn. Through a parameter, a field, or a mut binding, the instance's size isn't known:

Vyi · does not compile
fn size(f: fn() i32) i32 {
    con inst = *f   // error: cannot dereference this fn() i32
    return 0
}

A closure's own lifetime can be written too, by putting the literal in parentheses and annotating the whole, as in ((p: *mut Point) *mut i32 => &p.x) '(owner). The closures section of the memory model reference covers it, along with what a call through an interface value or a C function requires of its arguments.

See also: the memory model reference and the @mem package.