Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Working with Arrays in Rust

2 min read .
Working with Arrays in Rust

An array in Rust is a fixed-size collection whose elements all have the same type. Arrays are useful when the number of elements is known at compile time and should not grow or shrink during execution.

What Is an Array in Rust?

The type of an array includes both its element type and its length. For example, [i32; 5] is an array containing exactly five i32 values. A differently sized array is a different type.

Declare Arrays

fn main() {
    let numbers = [1, 2, 3, 4, 5];
    let zeros: [i32; 5] = [0; 5];

    println!("{:?}", numbers);
    println!("{:?}", zeros);
}
  • numbers initializes each element explicitly.
  • [0; 5] repeats the value 0 five times.

Access and Update Elements

fn main() {
    let mut fruits = ["apple", "banana", "cherry"];
    println!("The first fruit is: {}", fruits[0]);

    fruits[1] = "blueberry";
    println!("Updated array: {:?}", fruits);
}

The array must be declared with mut before its elements can be reassigned.

Borrow an Array Slice

A slice references a range of elements without copying them:

fn main() {
    let numbers = [10, 20, 30, 40, 50];
    let slice = &numbers[1..4];
    println!("The slice is: {:?}", slice);
}

The range 1..4 includes indexes 1, 2, and 3.

Common Array Operations

1. Get the Length

let arr = [1, 2, 3, 4];
println!("Length: {}", arr.len());

2. Iterate

let languages = ["Rust", "Python", "Java"];

for language in &languages {
    println!("I like {}", language);
}

3. Iterate in Reverse

let numbers = [1, 2, 3, 4, 5];
let reversed: Vec<_> = numbers.iter().rev().copied().collect();
println!("Reversed: {:?}", reversed);

If you only need to process values in reverse order, you can use the reversed iterator directly instead of collecting into a Vec.

4. Sort an Array

Arrays can use slice sorting methods:

let mut numbers = [5, 3, 8, 1];
numbers.sort();
println!("Sorted: {:?}", numbers);

Multidimensional Arrays

Nested arrays can represent fixed-size matrices or grids:

let matrix: [[i32; 3]; 2] = [
    [1, 2, 3],
    [4, 5, 6],
];

println!("Matrix: {:?}", matrix);

Handle Out-of-Bounds Access Safely

Direct indexing panics if the index is outside the array. Use get() when the index is not guaranteed to be valid:

let arr = [1, 2, 3];

match arr.get(5) {
    Some(value) => println!("Value: {}", value),
    None => println!("Index out of bounds!"),
}

get() returns an Option<&T> rather than panicking.

Best Practices

  1. Use arrays when the size is fixed and meaningful to the type.
  2. Prefer iterators over manual indexing when you simply need to visit elements.
  3. Use get() for indexes that come from users, external data, or calculations that may be invalid.
  4. Use Vec<T> when the collection needs to grow or shrink dynamically.
  5. Accept slices (&[T]) in functions when callers should be able to pass either arrays or vectors.

Conclusion

Rust arrays provide compact, fixed-size storage with strong compile-time type information. Combined with slices and iterator methods, they cover many cases where a collection’s size is known in advance, while Vec<T> remains the better choice for dynamically sized data.

Related Posts

chevron-up