Skip to main content

Arrays

An array holds a fixed number of values of one type, in order. T[] is an array of T, and a literal lists its values in brackets:

let numbers : i32[] = [1, 2, 3, 4, 5]
let names : string[] = ["one", "two", "three"]

An array is fixed by default: its values can't be changed. Add mut for one you can write to. mut i32[10] makes one with room for ten values:

let items = mut i32[10]
items[0] = 100

Reading an array​

An array knows its size, and an element is read by its index, counting from 0:

let numbers : i32[] = [1, 2, 3, 4, 5]
println("${numbers.size}")
println("${numbers[0]}")

Reading or writing past the end stops the program with a fault, rather than reading whatever is beyond it.

A for loop goes through an array's values in order:

let numbers : i32[] = [1, 2, 3]
for (value in numbers) {
println("${value}")
}

Arrays of classes​

An array can hold a class's instances too. A mut one starts empty, so its element type is a maybe, T?:

class Sensor(let name: string)

entrypoint main() {
let sensors = mut Sensor?[4]
sensors[0] = Sensor("left")
}

Other collections​

Arrays are V0's only collection. Lists, sets and maps come with generics.