Vector (Vec) in Rust

 

What is a Vector? 

A Vector (Vec<T>) in Rust is a dynamic array that can grow and shrink as needed. Unlike arrays, vectors don’t have a fixed size, making them the go-to choice for handling lists of items when you don’t know the exact length beforehand.

Creating a Vector

fn main() {
    let mut numbers = vec![1, 2, 3, 4, 5];
    println!("First element: {}", numbers[0]);
}
  • Uses vec![] macro to create a new vector.
  • Dynamically sized (Unlike arrays which are fixed).
  • Can be modified (add, remove, update elements).

Adding and Removing Elements 

Vectors are flexible! You can push, pop, and remove elements dynamically.

Adding Elements

fn main() {
    let mut numbers = Vec::new();
    numbers.push(10);
    numbers.push(20);
    println!("Vector: {:?}", numbers);
}

 .push(value) adds a new element at the end.

Removing Elements

fn main() {
    let mut numbers = vec![1, 2, 3];
    numbers.pop();
    println!("After pop: {:?}", numbers);
}

 .pop() removes the last element.

Iterating Over a Vector

Vectors support iteration using loops.

fn main() {
    let numbers = vec![100, 200, 300];
    for num in &numbers {
        println!("Value: {}", num);
    }
}

Use &numbers to avoid ownership issues.

Why Use Vectors? 

  • Dynamic sizing makes them super flexible.
  • Heap-allocated storage is efficient for large data.
  • Easy to modify (adding and removing elements).

So, when you need a resizable list, let Rust Vec-tor your way to success!

Post a Comment

0 Comments