Arrays, Spans, and Fixed-Size Arrays

An Array is a growable collection of objects of the same type T, stored in contiguous memory. Because Cairo's memory is write-once, values stored in an array cannot be modified. The only operation that can be performed on an array is appending elements at the end, or removing elements from the front.

A Span is the [snapshot][snapshot] of an Array - representing a range of elements in the array that can not be appended to. If the array is modified, the associated span will not be affected.

A Fixed-Size Array is an immutable sequence of elements of the same type stored in contiguous memory. Its size and contents are known at compile time, and they're useful to hard-code a sequence of data in your program.

fn main() {
    // Initialize an empty array
    let mut arr = array![];

    // Append elements to the array
    arr.append(1);
    arr.append(2);
    arr.append(3);

    // Indexing starts at 0.
    println!("First element of the array: {}", *arr[0]);
    println!("Second element of the array: {}", *arr[1]);

    // `len()` returns the number of elements in the array.
    println!("Number of elements in the array: {}", arr.len());

    // A span is a snapshot of the array at a certain state.
    let span = arr.span();

    // `pop_front()` removes the first element from the array.
    let _ = arr.pop_front();

    // But the span is not affected by the pop: it has the same state as when the snapshot was
    // taken.
    println!("First element in span: {}", *span[0]);

    // Fixed-size array type
    let xs: [u32; 3] = [1, 2, 3];

    // All elements can be initialized to the same value.
    let ys: [u32; 3] = [0; 3];

    println!("xs: {:?}", xs);
    println!("ys: {:?}", ys);

    // Fixed-size arrays can be converted to spans for operations.
    println!("ys first element: {}", *xs.span()[0]);
}

See also: