An array is a stack-allocated, statically-sized list of objects of a single type.
Arrays are usually created by enclosing a list of elements of a given type between square brackets. The type of an array is denoted with the special syntax: [T; N]
where T
is the type of its elements and N
their count, both of which must be known at compilation time.
For example, [4u64, 5, 6]
is a 3-element array of type [u64; 3]
. Note: 5
and 6
are inferred to be of type u64
.
fn main() {
// Arrays have a fixed size.
// All elements are of the same type.
let array = [1, 2, 3, 4, 5];
// Create an array of 20 elements where all elements are the same.
// The size should be a compile-time constant.
let ones = [1; 20];
// Get the length of an array.
println!("Length of ones: {}", ones.len());
// Access an element of an array.
// Indexing starts at 0.
println!("Second element of array: {}", array[1]);
// Run-time bounds-check.
// This panics with 'index out of bounds: the len is 5 but the index is 5'.
println!("Non existant element of array: {}", array[5]);
}
Pattern-matching on arrays (or slices) is not supported in stable Rust (see #23121 and slice patterns).
Rust does not support genericity of type-level numerals (see RFCs#1657). Therefore, it is not possible to simply implement a trait for all arrays (of all sizes). As a result, the standard traits are only implemented for arrays up to a limited number of elements (last checked, up to 32 included). Arrays with more elements are supported, but do not implement the standard traits (see docs).
These restrictions will hopefully be lifted in the future.