Start Coding

Rust Arrays

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.

Declaring Arrays

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

Accessing Array Elements

Access array elements using zero-based indexing:

let first = numbers[0];
let third = numbers[2];

Array Length

Get the length of an array using the len() method:

let length = numbers.len(); // Returns 5

Iterating Over Arrays

Use a for loop to iterate over array elements:

for number in numbers.iter() {
    println!("{}", number);
}

Mutability

Arrays are immutable by default. To create a mutable array:

let mut mutable_numbers = [1, 2, 3, 4, 5];
mutable_numbers[2] = 10;

Array Slices

Create a view into a portion of an array using slices:

let slice = &numbers[1..4]; // Creates a slice of [2, 3, 4]

Important Considerations

  • Arrays have a fixed size at compile-time.
  • All elements must be of the same type.
  • Rust performs bounds checking at runtime to prevent buffer overflows.
  • For dynamic-sized collections, consider using Vectors.

Common Operations

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.