Rust - Arrays and Vectors

In Rust, there are different ways to store a collection of values. The most common types for such collections are arrays and vectors (Vec), each having distinct characteristics and use cases.

Bernd Fischer

Bernd Fischer

14. Oct 2024 · 3 min read

Rust - Arrays and Vectors

Arrays and vectors are the fundamental data types in Rust when it comes to storing lists. Arrays are efficient for fixed amounts of data, while vectors (Vec) are ideal for dynamically growing or shrinking lists. Rust's strict rules on borrowing and ownership help avoid errors in memory management and ensure runtime safety.

1. Arrays in Rust

An array is a fixed, immutable collection of values of the same type. The size of an array is set at compile time and cannot be changed later.

Example: Creating an array

fn main() {
    let numbers: [i32; 5] = [1, 2, 3, 4, 5];
    println!("{:?}", numbers);
}

In this example, an array numbers is created, consisting of five integers (i32). The size [i32; 5] indicates that the array has five elements.

Properties of arrays

  • Fixed size: The size of an array is set when it is created and cannot be changed.
  • Element access: Access to array elements is via indices, starting at 0.
  • Stack allocated: Elements are stored on the stack.

Example: Accessing array elements

fn main() {
    let numbers = [1, 2, 3, 4, 5];
    println!("Erstes Element: {}", numbers[0]);
    println!("Drittes Element: {}", numbers[2]);
}

Rust checks whether the index is within the array bounds. If an attempt is made to access an invalid index, the program terminates with a panic error.

2. Vectors (Vec)

A vector (Vec<T>) in Rust is a dynamically sized list of elements. Unlike arrays, a vector's size can be changed at runtime by adding or removing elements.

Example: Creating a vector

fn main() {
    let mut numbers = Vec::new();
    numbers.push(1);
    numbers.push(2);
    numbers.push(3);
    println!("{:?}", numbers);
}

In this example, an empty vector numbers is created, and then elements are added using the method push.

Properties of vectors

  • Dynamic size: Vectors can be grown or shrunk at runtime.
  • Heap allocated: Unlike arrays, vectors are stored on the heap, enabling size changes at runtime.
  • Mutability: A vector must be declared as mut if it is to be modified.

Example: Accessing vector elements

fn main() {
    let numbers = vec![10, 20, 30, 40];
    println!("Zweites Element: {}", numbers[1]);
}

Example: Removing elements

fn main() {
    let mut numbers = vec![1, 2, 3, 4];
    numbers.pop(); // Letztes Element entfernen
    println!("{:?}", numbers); // Gibt: [1, 2, 3]
}

3. Differences in usage

fn main() {
    let array = [1, 2, 3];   // Festes Array
    let mut vector = vec![1, 2, 3]; // Dynamischer Vektor

    vector.push(4);          // Hinzufügen eines Wertes (nur bei Vec)
    println!("{:?}", array);
    println!("{:?}", vector);
}

4. Iterating over arrays and vectors

Both arrays and vectors can be iterated over using a for loop.

Example: Iterating over an array

fn main() {
    let numbers = [10, 20, 30];
    for num in numbers.iter() {
        println!("Wert: {}", num);
    }
}

Example: Iterating over a vector

fn main() {
    let numbers = vec![5, 10, 15];
    for num in &numbers {
        println!("Wert: {}", num);
    }
}

With vectors, a reference &numbers is used to ensure that the vector is not consumed and remains available for further use.