Spec chapters

11. Arrays and slices

[N]T is a value: N elements stored inline, copied on assignment. Write a literal as [3]i64{ 1, 2, 3 } or [_]i64{ 1, 2, 3 } (length from the elements), or fill one with @splat(v) where the type is known. a[i] is bounds-checked; @len(a) is N.

[]T is a slice: a read-only view of consecutive elements of an array, written a[lo..hi] or a[lo..] (an inout slice is writable; section 12). Slices are second-class (E116): a slice can be a parameter type, an argument, the subject of for, a local const or inout, or a function’s result (below), and nothing else. It cannot be stored in a var or a field. So a view can never outlive the array it looks into, without lifetime annotations. An array is not implicitly a slice: pass a[0..] (E103).

const s = x[lo..hi] names a part of a variable, or of a part of one (E116 for a temporary, or a view through a pointer); const t = s names a slice again, and const t = if (c) x[1..] else y[1..] either part. It is read-only, and it borrows x (each variable it may view: both x and y for that if) until its last use: while s is used later, on a path that can really get there, x cannot be moved, assigned, resized, passed as inout or have its elements written (E149). Reading x is always fine, and after the last use of s all of it is allowed again. A defer that uses s is a use at the end of the block. A slice of a slice borrows what the first one does.

// expect: 10
// expect: 5
// expect: 3
uses io

fn sum(xs: []i64) i64 {
    var total = 0
    for (xs) |x| {
        total = total + x
    }
    return total
}

fn main(io: Io) void {
    const a = [4]i64{ 1, 2, 3, 4 }
    io.print(sum(a[0..]))
    io.print(sum(a[1..3]))
    const zeros: [3]i64 = @splat(1)
    io.print(sum(zeros[0..]))
}
// expect: GET
// expect: GET /a!
uses alloc, io

fn main(io: Io, a: Allocator) void {
    var line = a.concat("GET /a", "")
    defer a.free(line)
    const method = line[0..3]
    io.print(method)
    a.push(&line, '!')          // method is finished with
    io.print(line)
}
// error: E149
uses alloc, io

fn main(io: Io, a: Allocator) void {
    var line = a.concat("GET /a", "")
    defer a.free(line)
    const method = line[0..3]
    a.push(&line, '!')          // may move the bytes method looks at
    io.print(method)
}

inout s = &x[lo..hi] is a writable local slice of a var array, a var Buf, or a part of one, or of another writable slice (E105 for anything read-only, E116 for anything but &x[lo..hi]). s[i] = v writes through it, and s itself cannot be reassigned (E105); one that is never written should be a const (E111). It has x to itself: at any moment a place has either any number of read-only slices or one writable slice. While s is used later, everything in the rule above is refused, and so is reading x in any way, @len(x) too (E149). A slice taken from s goes through it: s waits while that slice is in use, and is usable again after its last use. Two parts of one array are one place, even when their ranges do not overlap; two fields of a struct are two places.

// expect: 9
// expect: 5
uses io

fn main(io: Io) void {
    var x = [3]i64{ 1, 2, 3 }
    inout s = &x[1..]
    s[0] = 4
    s[1] = 5
    inout t = &s[0..1]
    t[0] = 9
    io.print(s[0])
    io.print(x[2])              // s is finished with
}
// error: E149
uses io

fn main(io: Io) void {
    var x = [3]i64{ 1, 2, 3 }
    inout s = &x[1..]
    io.print(x[0])              // s is written below
    s[0] = 4
}
// error: E116
uses io

fn main(io: Io) void {
    const a = [3]i64{ 1, 2, 3 }
    var view = a[0..2]
    io.print(@len(view))
}

Slices as results. A function may return []T, ?[]T, ![]T or !?[]T: a view into what one of its plain (read-only) parameters points to, a string literal, or null. Its signature says which parameters the result views, and callers rely on that alone, never on the body:

  • fn header(req: Request, name: []u8) ?[]u8 from req: the parameters named after from. from is a word only there.
  • Without from, a method’s result views self, if self can hold elements of the result’s type; any other function’s views every plain parameter that can. A parameter can when such elements are behind a pointer in it: a slice, a Buf or a str of them, or a struct, array or optional holding one. So fn trim(s: []u8) []u8 views s.

The body is checked against the signature (E151): what it returns must view only those parameters, and not memory that ends with the call: a local, a sink or inout parameter, or an array inside a parameter (or a loop variable), which is the function’s own copy. from must name plain parameters that can hold such elements (E152).

At a call, the result views the arguments passed for those parameters (a literal or a constant: nothing). It is a local slice like const s = x[lo..hi] of each of them (E149), and can be named with const, unwrapped with orelse or if (opt) |s|, passed on, looped over or returned in turn. A function value’s type has no parameter names, so a call through one views every plain parameter that can.

// expect: [hi there]
// expect: example
// expect: none
uses io, alloc

fn trim(s: []u8) []u8 {
    var lo = 0
    var hi = @len(s)
    while (lo < hi and s[lo] == ' ') {
        lo = lo + 1
    }
    while (hi > lo and s[hi - 1] == ' ') {
        hi = hi - 1
    }
    return s[lo..hi]
}

// The value after "name=" in text; name is only compared.
fn value(text: []u8, name: []u8) ?[]u8 from text {
    if (@len(text) > @len(name) and text[0..@len(name)] == name and text[@len(name)] == '=') {
        return text[@len(name) + 1..]
    }
    return null
}

fn main(io: Io, a: Allocator) void {
    const line = a.concat("  hi there ", "")
    defer a.free(line)
    io.print("[", trim(line), "]")
    var key = a.concat("host", "")
    defer a.free(key)
    const got = value("host=example", key) orelse "none"
    a.push(&key, '!')           // not lent: `from text`
    io.print(got)
    io.print(value("port=1", key) orelse "none")
}
// error: E151
uses alloc

fn copy_of(a: Allocator, s: []u8) []u8 {
    const b = a.concat(s, "")
    defer a.free(b)
    return b[0..]               // freed when the function returns
}

fn main() void {
}
// error: E149
uses alloc, io

fn trim(s: []u8) []u8 {
    return s[1..]
}

fn main(io: Io, a: Allocator) void {
    var line = a.concat(" x", "")
    defer a.free(line)
    const t = trim(line)
    a.push(&line, '!')          // may move the bytes t looks at
    io.print(t)
}