Indexing and Iteration
The elements of an array are reached the same way as any sequence — by position or in a loop.
Indexing
Use [i] to read or write a single element. The index is zero-based, so valid indices run from 0 to length - 1:
var row = [10, 20, 30];
let first = row[0]; // 10
row[2] = 99; // row == [10, 20, 99]
Writing an element requires the array to be mutable — bound with var. Through a let binding the elements are read-only, matching the deep mutability rule for value types.
Iteration
for … in walks every element in order, binding each to the loop variable:
let nums = [1, 2, 3, 4, 5];
var sum = 0;
for n in nums {
sum += n;
}
// sum == 15
The loop covers exactly length elements — and because an array's length is a compile-time constant, the compiler knows the trip count up front. See for for the full loop syntax.
Indexing with a Range
Indexing with a range instead of a single position produces a slice over part of the array rather than one element:
let data = [1, 2, 3, 4, 5];
let middle = data[1..4]; // Slice<int> viewing 2, 3, 4
This is covered in Arrays as Slices.
See Also
- Arrays — the array type and its value semantics
- Arrays as Slices — range sub-slicing and passing arrays to functions
for— iterating over a sequence- Mutability of Structs — why element writes need
var
Overview
An array T[N] is a fixed-size sequence of N values of type T, stored inline. The count N is part of the type and fixed at compile time, so int32[3] and int32[4] are different types. An array is its elements — it owns them directly, with no pointer or header in between.
Arrays as Slices
An array owns its storage; a slice (Slice<T>) is a lightweight view into storage owned elsewhere. Because an array is contiguous elements with a known length, it can always be viewed as a slice — and this is how you hand an array to code without copying it.