Skip to content
Sword

Arrays and slices

An array has its length in its type and is copied when assigned:

func main() int {
mut digits := [4]i32{7, 8, 9, 10}
copy := digits // a real copy
digits[0] = 0
return int(copy[0]) // still 7
}

[64]u8{} is the zeroed array. Any other literal has to be written out in full.

A slice is a pointer and a length — two words that point at somebody else’s elements:

func sum(xs []i64) i64 {
mut total i64 = 0
for i in 0..xs.len {
total += xs[i]
}
return total
}
func main() int {
values := [6]i64{1, 2, 3, 4, 5, 6}
all := values[..]
middle := values[2..4]
return int(sum(all) + sum(middle))
}

Copying a slice copies those two words, so the elements stay shared. That is the distinction to keep in mind: arrays are values, slices are views.

Indexing is checked. xs[99] on a six-element slice aborts with a message naming the line, unless you compiled with --mode=fast.