Arrays and Fixed-Size Arrays

10.1 Dynamic Arrays

Bounds-checked: an out-of-range index panics. Use arr[i] or { default } for safe access.

Arrays are value types semantically, but assignment of a mutable array requires an explicit .clone() (or mut b := a.clone()) to avoid aliasing surprises. The compiler enforces this in some cases.

mut nums := [1, 2, 3]                  // []int
mut empty := []string{}
mut pre := []int{len: 5}               // [0, 0, 0, 0, 0]
mut filled := []int{len: 3, init: 7}   // [7, 7, 7]
mut idx := []int{len: 5, init: index * 2}   // [0, 2, 4, 6, 8]
mut big := []int{cap: 1000}            // preallocated capacity
nums << 4
nums << [5, 6]
nums.insert(0, 0)
nums.delete(1)
println(nums.len)
println(nums.cap)
println(nums.first())
println(nums.last())
println(nums.pop())
println(nums.contains(3))
println(3 in nums)
println(nums.index(3))
println(nums[1..3])                    // slice (shares memory)
println(nums[..2])
println(nums[2..])
copy := nums.clone()                   // explicit deep copy
nums.clear()

10.2 Array Methods: Functional Style

import arrays: sum, max, min, reduce, fold, group_by, chunk, window, flatten, uniq, zip (via arrays.group), find_first, index_of_first, distinct, and more.

nums := [5, 3, 8, 1, 9]
evens := nums.filter(it % 2 == 0)              // `it` = the current element
squares := nums.map(it * it)
strs := nums.map(it.str())
println(nums.any(it > 8))
println(nums.all(it > 0))
println(nums.count(it > 3))                    // newer versions
total := arrays.sum(nums) or { 0 }             // import arrays
biggest := arrays.max(nums) or { 0 }
reduced := arrays.reduce(nums, fn (acc int, x int) int { return acc + x }) or { 0 }
mut sorted := nums.clone()
sorted.sort()                                  // ascending
sorted.sort(a > b)                             // custom: descending
people.sort(a.age < b.age)                     // sort structs by field
sorted.sort_with_compare(fn (a &int, b &int) int { return *a - *b })
println(nums.sorted())                         // returns a new sorted array
println(nums.reverse())
println(nums.filter(it > 2).map(it * 10))      // chaining

10.3 Fixed-Size Arrays

mut fixed := [5]int{}              // stack-allocated, size known at compile time
fixed[0] = 10
arr := [1, 2, 3]!                  // the `!` suffix makes a fixed-size array literal
println(fixed.len)
dyn := fixed[..]                   // convert to a dynamic array (slice)

10.4 Multidimensional Arrays

mut grid := [][]int{len: 3, init: []int{len: 3}}
grid[1][2] = 5
matrix := [[1, 2], [3, 4]]
mut board := [3][3]u8{}            // fixed 2D