Ruta graveolens  ·  notes from a language experiment  ·  cultivated since 2025

Index Expressions

An index expression accesses an element of an array.

index_expr = expression "[" expression "]" ;

The expression before the brackets MUST have an array type [T; N].

The index expression MUST have an integer type (signed or unsigned: i8, i16, i32, i64, u8, u16, u32, u64, isize, or usize). A negative index value is not a compile-time type error; it is caught by bounds checking (a negative index always fails the bounds check and traps at runtime).

The type of an index expression is the element type T.

fn main() -> i32 {
    let arr: [i32; 3] = [10, 42, 100];
    arr[1]  // 42
}

Bounds Checking

For constant indices, bounds checking MUST be performed at compile time.

For variable indices, bounds checking MUST be performed at runtime.

An out-of-bounds access MUST cause a runtime panic.

fn main() -> i32 {
    let arr: [i32; 3] = [1, 2, 3];
    arr[5]  // Compile-time error: index out of bounds
}
fn main() -> i32 {
    let arr: [i32; 3] = [1, 2, 3];
    let idx = 5;
    arr[idx]  // Runtime error: index out of bounds
}

Index Assignment

For mutable arrays, elements can be assigned using index expressions.

fn main() -> i32 {
    let mut arr: [i32; 2] = [0, 0];
    arr[0] = 20;
    arr[1] = 22;
    arr[0] + arr[1]  // 42
}