Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Arrays

ItemSummary
newCreates an empty array
new_filledCreates an array of len elements, each a copy of value
lenReturns the number of elements
containsReturns whether any element equals value
pushAppends value to the end of the array
insertInserts value at index, moving the element there and everything after it one place toward the end
popRemoves the last element and returns it, or returns null if the array is empty
removeRemoves the element at index and returns it, moving everything after it one place toward the start
firstReturns the first element, or null if the array is empty
shufflePuts the elements in a random order
extendAppends every element of other, in order
enumerateReturns a new array pairing each element with its index
flatReturns a new array with the elements of each inner array, in order
chooseReturns a random element, or null if the array is empty
joinReturns the strings joined together with separator between each one
is_emptyReturns whether the array has no elements
maxReturns the maximum value present in the array
minReturns the minimum value present in the array
sumReturns the sum of all values in the array
sort_by_intSorts the array in ascending order of keys, where keys[i] is the key for element i
sort_by_floatSorts the array in ascending order of keys, where keys[i] is the key for element i
argsortCompares all elements in the array and returns a new array with the indicies sorted
reorderReplaces the array’s contents with the elements at indices, in that order
dedupedReturns a new array without repeated elements, keeping the first occurrence of each value in its original order
reversedReturns a new array with the elements in reverse order
to_dictReturns a dictionary built from (key, value) pairs, the reverse of a dictionary’s pairs

Associated Functions

new

fn new() -> [T]

Creates an empty array. This is the same as writing [], and like [] it needs a type annotation if nothing else tells the compiler what it will hold.

let xs: [int] = array::new();
xs.push(1); // xs is now [1]

new_filled

fn new_filled(value: T, len: int) -> [T]

Creates an array of len elements, each a copy of value. The copies are deep, so filling with an array gives each slot its own array.

A len that is negative, or too large for an array to hold, is a runtime error.

let grid = array::new_filled([0, 0], 2);
grid[0].push(1);
// grid is [[0, 0, 1], [0, 0]]

Methods

len

fn len(self) -> int

Returns the number of elements.

let n = [3, 1, 2].len(); // 3

contains

fn contains(self, value: T) -> bool

Returns whether any element equals value. This is the same check as the in operator.

let xs = [1, 2, 3];
let a = xs.contains(2); // true
let b = 2 in xs;        // true

push

fn push(self, value: T)

Appends value to the end of the array.

let xs = [1, 2];
xs.push(3); // xs is now [1, 2, 3]

insert

fn insert(self, index: int, value: T)

Inserts value at index, moving the element there and everything after it one place toward the end. An index equal to the array’s length appends.

An index that is negative or past the end is a runtime error.

let xs = [1, 3];
xs.insert(1, 2); // xs is now [1, 2, 3]
xs.insert(3, 4); // xs is now [1, 2, 3, 4]

pop

fn pop(self) -> T?

Removes the last element and returns it, or returns null if the array is empty.

let xs = [1, 2];
let last = xs.pop(); // 2, and xs is now [1]

remove

fn remove(self, index: int) -> T

Removes the element at index and returns it, moving everything after it one place toward the start.

An index that is negative or not below the array’s length is a runtime error.

let xs = [1, 2, 3];
let middle = xs.remove(1); // 2, and xs is now [1, 3]

first

fn first(self) -> T?

Returns the first element, or null if the array is empty.

let xs = [1, 2];
let a = xs.first(); // 1

shuffle

fn shuffle(self)

Puts the elements in a random order.

let deck = [1, 2, 3, 4];
deck.shuffle();

extend

fn extend(self, other: [T])

Appends every element of other, in order. other is unchanged.

let xs = [1, 2];
xs.extend([3, 4]); // xs is now [1, 2, 3, 4]

enumerate

fn enumerate(self) -> [(int, T)]

Returns a new array pairing each element with its index.

for (i, name) in ["ant", "bee"].enumerate() {
    print(f"{i}: {name}"); // 0: ant, then 1: bee
}

flat

fn flat(self: [[T]]) -> [T]

Returns a new array with the elements of each inner array, in order. Only one level is removed: a [[[int]]] flattens to a [[int]].

let xs = [[1, 2], [], [3]].flat(); // [1, 2, 3]

choose

fn choose(self) -> T?

Returns a random element, or null if the array is empty.

let loot = ["sword", "shield", "potion"];
let drop = loot.choose() ?? "nothing";

join

fn join(self: [str], separator: str) -> str

Returns the strings joined together with separator between each one. Only [str] has join, so convert other arrays first:

let a = ["a", "b", "c"].join(", "); // "a, b, c"
let b = (for n in [1, 2, 3] collect n.to_str()).join("-"); // "1-2-3"

is_empty

fn is_empty(self) -> bool

Returns whether the array has no elements.

let xs: [int] = [];
let empty = xs.is_empty(); // true

max

fn max(self: [int]) -> int?
fn max(self: [float]) -> float?

Returns the maximum value present in the array.

let a: [int] = [0, 1, 2];
let int_max = a.max(); // 2

let b: [float] = [0.0, 1.0, 2.0];
let float_max = b.max(); // 2.0

min

fn min(self: [int]) -> int?
fn min(self: [float]) -> float?

Returns the minimum value present in the array.

let a: [int] = [0, 1, 2];
let int_min = a.min(); // 0

let b: [float] = [0.0, 1.0, 2.0];
let float_min = b.min(); // 0.0

sum

fn sum(self: [int]) -> int
fn sum(self: [float]) -> float

Returns the sum of all values in the array. A sum of ints that overflows is a runtime error.

let a: [int] = [0, 1, 2];
let int_sum = a.sum(); // 3

let b: [float] = [0.0, 1.0, 2.0];
let float_sum = b.sum(); // 3.0

sort_by_int

fn sort_by_int(self, keys: [int])

Sorts the array in ascending order of keys, where keys[i] is the key for element i. Equal keys keep their original order. keys is unchanged.

let names = ["cat", "ant", "bee"];
names.sort_by_int([3, 1, 2]); // names is now ["ant", "bee", "cat"]

keys should be as long as the array. An element without a key is dropped from the array, and extra keys are ignored.

sort_by_float

fn sort_by_float(self, keys: [float])

Sorts the array in ascending order of keys, where keys[i] is the key for element i. Equal keys keep their original order. keys is unchanged.

let names = ["far", "near", "mid"];
names.sort_by_float([9.5, 0.5, 3.0]); // names is now ["near", "mid", "far"]

keys should be as long as the array. An element without a key is dropped from the array, and extra keys are ignored.

argsort

fn argsort(self: [int]) -> [int]
fn argsort(self: [float]) -> [int]

Compares all elements in the array and returns a new array with the indicies sorted. For example, if the maximum value in this array is at index 3, the first element of the returned array will be 3.

let a = [5, 0, 2, 4];
let a_sorted = [0, 3, 2, 1];

let b = [5.0, 0.0, 2.0, 4.0];
let b_sorted = [0, 3, 2, 1];

reorder

fn reorder(self, indices: [int])

Replaces the array’s contents with the elements at indices, in that order. The indices don’t have to cover every element once: the array ends up as long as indices, and an index can repeat.

An index that is negative or past the end is a runtime error, and the array is left unchanged.

let xs = ["a", "b", "c"];
xs.reorder([2, 0, 1]); // xs is now ["c", "a", "b"]
xs.reorder([0, 0]);    // xs is now ["c", "c"]

deduped

fn deduped(self) -> [T]

Returns a new array without repeated elements, keeping the first occurrence of each value in its original order. Elements are compared with ==, the same check as contains. Unlike Rust’s dedup, the repeats don’t have to be next to each other. The array itself is unchanged.

let xs = [3, 1, 3, 2, 1];
let ys = xs.deduped(); // [3, 1, 2]

reversed

fn reversed(self) -> [T]

Returns a new array with the elements in reverse order. The array itself is unchanged.

let xs = [1, 2, 3];
let ys = xs.reversed(); // [3, 2, 1]

for x in xs.reversed() {
    print(x); // 3, then 2, then 1
}

to_dict

fn to_dict(self: [(str, T)]) -> ~{T}

Returns a dictionary built from (key, value) pairs, the reverse of a dictionary’s pairs. When a key appears more than once, the dictionary holds its last value, in the position where the key first appeared.

let scores = [("ada", 3), ("bob", 5)].to_dict(); // ~{ ada = 3, bob = 5 }

let names = ["ada", "grace"];
let lengths = (for name in names collect (name, name.len())).to_dict();
// lengths is ~{ ada = 3, grace = 5 }