Fixed-Size Arrays
Array Literals
array_literal = "[" [ expression { "," expression } ] "]" ;
An array literal creates an array with the given elements.
All elements MUST have the same type.
The number of elements MUST match the declared array size.
fn main() -> i32 {
let arr: [i32; 3] = [10, 20, 12];
arr[0] + arr[1] + arr[2] // 42
}
Array Indexing
Array elements are accessed using bracket notation arr[index].
The index MUST be an integer type.
fn main() -> i32 {
let arr: [i32; 3] = [100, 42, 200];
arr[1] // 42
}
Bounds Checking
For constant indices, bounds MUST be checked at compile time.
For variable indices, bounds MUST be checked at runtime.
Out-of-bounds access MUST cause a runtime panic.
Mutable Arrays
Mutable arrays allow element assignment.
fn main() -> i32 {
let mut arr: [i32; 2] = [0, 0];
arr[0] = 20;
arr[1] = 22;
arr[0] + arr[1] // 42
}
Array Type Syntax
array_type = "[" type ";" INTEGER "]" ;
The size MUST be a non-negative integer literal.
Nested Arrays
Arrays MAY contain other arrays as elements, forming multi-dimensional arrays.
Nested arrays are indexed using chained bracket notation, evaluated left to right.
fn main() -> i32 {
let matrix: [[i32; 2]; 2] = [[1, 2], [3, 4]];
matrix[1][1] // 4
}
Arrays in Structs
Struct fields MAY have array types.
Array fields are accessed by combining field access with array indexing.
struct Container { values: [i32; 3] }
fn main() -> i32 {
let c = Container { values: [10, 20, 30] };
c.values[1] // 20
}
Arrays as Function Parameters
Functions MAY accept arrays as parameters.
Array parameters are passed by value; the entire array is copied to the function.
fn sum(arr: [i32; 3]) -> i32 {
arr[0] + arr[1] + arr[2]
}
fn main() -> i32 {
let data: [i32; 3] = [10, 20, 12];
sum(data) // 42
}