Arrays in Rust are fixed-size collections of elements, all of the same data type. They provide efficient, stack-allocated storage for a known number of items.
To declare an array in Rust, use square brackets []
with the type and size specified:
let numbers: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0; 10]; // Creates an array of 10 zeros
Access array elements using zero-based indexing:
let first = numbers[0];
let third = numbers[2];
Get the length of an array using the len()
method:
let length = numbers.len(); // Returns 5
Use a for loop to iterate over array elements:
for number in numbers.iter() {
println!("{}", number);
}
Arrays are immutable by default. To create a mutable array:
let mut mutable_numbers = [1, 2, 3, 4, 5];
mutable_numbers[2] = 10;
Create a view into a portion of an array using slices:
let slice = &numbers[1..4]; // Creates a slice of [2, 3, 4]
Operation | Syntax |
---|---|
Create | let arr = [1, 2, 3, 4, 5]; |
Access | let first = arr[0]; |
Length | let len = arr.len(); |
Iterate | for &item in arr.iter() {} |
Slice | let slice = &arr[1..3]; |
Arrays in Rust provide a powerful tool for working with fixed-size collections. They offer performance benefits and compile-time size checking, making them ideal for scenarios where the number of elements is known in advance.
For more advanced data structures, explore Vectors and Hash Maps in Rust.