array
A homogeneous, ordered, variable-length collection, written by suffixing [] to the element type.
const bearings: float32[] = [87.5, 91.0, 274.25];
const grid: int32[][] = [[1], [2, 3]];
const pending: string[] = [];Elements
The [] suffix repeats, so int32[][] is an array of arrays of int32. The element type may be any
type, including the struct being declared, which is how a recursive type holds its children.
- Every element of an array has one type.
- Two array types are assignable when their element types are.
- An empty
[]takes its element type from context: a declared type, a parameter, or an ascription. lengthreports the count, always as auint32.
struct Waypoint {
name: string;
legs: Waypoint[];
}Indexing and slicing
xs[i] selects one element and xs[a..b] selects a range. Both count from zero, and the slice is
inclusive at both ends.
- An index is an integer type, and an index past the end is a runtime failure that
trycatches. - A slice never fails. Bounds are clamped into the array, and a slice whose clamped bounds cross is the empty array.
lastreports the final element and fails on an empty array.
const bearings: float32[] = [87.5, 91.0, 274.25];
length(bearings) // => 3
bearings[(0: uint32)] // => 87.5
bearings[(1: uint32)..(9: uint32)] // => [91, 274.25]
try(bearings[(7: uint32)]) // => none
last(bearings) // => 274.25xs[a..b] includes both ends, unlike substring, which takes the half-open range [start, end). A
slice clamps out-of-range bounds and never fails, where substring reports a range past the end as a
runtime failure.
Concatenation
++ joins two arrays of the same element type and yields that type.
const head: uint8[] = [1, 2];
const rest: uint8[] = [3];
head ++ rest // => [1, 2, 3]
length(head ++ rest) // => 3Errors
An index that is not an integer
const bearings: float32[] = [87.5, 91.0];
const first: float32 = bearings[true]; // error: array-index-typeElements of more than one type
const mixed: string[] = ["air", 2]; // error: incompatible-branch-typesAn empty literal with no element type
An empty array carries no element to infer from, so the type has to come from somewhere else.
function count(pending: string[]) -> uint32 = {
let empty = []; // error: ambiguous-inferred-type
length(empty);
};Concatenating arrays of different element types
const bearings: float32[] = [87.5];
const names: string[] = ["air"];
const both: float32[] = bearings ++ names; // error: invalid-operand-typesRelated
- tuple — a fixed-length group whose elements may differ in type.
- primitives — the element types an array is usually built over.
- comprehension — building one from another.