Login Register

What is a Vector in Rust?

A Vector in Rust is a growable array that can store multiple values of the same type. You can define it using Vec<T>, where T is the type of the elements (like i32, String, etc.).

Vectors are stored on the heap, so you can add or remove elements while the program is running.

You donโ€™t need to know the number of elements in advance. Because all elements must have the same type.

The heap is a region of computer memory used for dynamic memory allocation. This means you can request memory at runtime (while the program is running).

Why Use Vectors In Rust Programming?

  • Dynamic Sizing: You donโ€™t need to know the number of elements in advance. A vector can grow when you add elements or shrink when you remove them.
  • Indexing: You can quickly access any element using its position number (starting from 0), just like arrays.
  • Contiguous Memory: All elements are stored together in one block of memory. This makes it fast to read, write, and loop through elements.
  • Versatility: Vectors can store any type of data, as long as that type can be copied or cloned.

How To Create a Vector?

There are a few ways to create vectors:

1. Using Vec: :new

This method creates an empty vector. You can add values later using the .push() method. This method is useful when you donโ€™t know the elements ahead of time.

fn main() {
let mut colors: Vec<&str> = Vec::new(); // Empty vector
colors.push("Red");
colors.push("Green");
colors.push("Blue");

println!("Colors: {:?}", colors); // Output: Colors: ["Red", "Green", "Blue"]
}

2. Using the vec! Macro

The vec! macro creates a vector with predefined elements. Itโ€™s a shortcut when you already know the elements you want to store.

fn main() {
let primes = vec![2, 3, 5, 7, 11]; // Vector with initial elements
println!("Prime numbers: {:?}", primes); // Output: Prime numbers: [2, 3, 5, 7, 11]
}
  • The vector is created with values already inside, so no need to push each element manually.

How To Access Elements in a Vector

Vectors store elements in zero-based indexing, so the first element is at index 0. There are two main ways to access elements:

1. Using Indexing ( [] )

You can directly access an element by its index. If the index is invalid, Rust will panic at runtime.

For example:

fn main() {
let fruits = vec!["Apple", "Banana", "Cherry"];
println!("Second fruit: {}", fruits[1]); // Output: Second fruit: Banana
}
  • In this code, we accessed the second element (index 1) directly. If we try fruits[5], the program would crash.

2. Using .get() Method

A .get(index) is safer because it returns an Option. This prevents runtime panic and allows you to handle errors gracefully.

fn main() {
let numbers = vec![100, 200, 300];

match numbers.get(5) {
Some(num) => println!("Found: {}", num),
None => println!("Oops! Index not found."),
}
}

Output:

Oops! Index not found.

How To Modify a Vector?

To modify a vector, you must declare it as mut (mutable).

1) Adding Elements

  • .push(value) adds a value at the end of the vector.
  • .insert(index, value) adds a value at a specific position, shifting other elements.
fn main() {
let mut colors = vec!["Red", "Green", "Blue"];

colors.push("Yellow"); // Add at the end
colors.insert(1, "Orange"); // Insert "Orange" at index 1

println!("Updated colors: {:?}", colors);
}

Output:

Updated colors: ["Red", "Orange", "Green", "Blue", "Yellow"]

Removing Elements

  • .pop() removes the last element and returns it as Option.
  • .remove(index) removes an element at a specific index and shifts the rest to the left.
fn main() {
let mut colors = vec!["Red", "Orange", "Green", "Blue", "Yellow"];

colors.pop(); // Remove last element ("Yellow")
colors.remove(2); // Remove element at index 2 ("Green")

println!("After removal: {:?}", colors);
}

Output:

After removal: ["Red", "Orange", "Blue"]

Iterating Over a Vector

Vectors store multiple values, and Rust provides several ways to loop through them. Iteration allows you to access each element one by one.

1. Using a for Loop

  • A for loop is the simplest way to go through all elements.
  • Use &numbers to borrow the vector, preventing ownership transfer. For example:
fn main() {
let fruits = vec!["Apple", "Banana", "Cherry"];

for fruit in &fruits {
println!("I like {}", fruit);
}
}

Output:

I like Apple
I like Banana
I like Cherry

2. Using an Iterator with .iter()

  • .iter() creates an iterator over references to the elements.
  • .for_each(|item| …) applies a closure to every element.

For example:

fn main() {
let numbers = vec![10, 20, 30];

numbers.iter().for_each(|n| println!("Number: {}", n));
}

Output:

Number: 10
Number: 20
Number: 30

Common Operations on Vectors

Rust provides many built-in methods to work with vectors efficiently.

1) Sorting a Vector

.sort() arranges the elements in ascending order.

fn main() {
let mut scores = vec![45, 10, 30, 25];
scores.sort();
println!("Sorted scores: {:?}", scores);
}

Output:

Sorted scores: [10, 25, 30, 45]

2) Reversing a Vector

.reverse() flips the order of elements in place.

Unique Example:

fn main() {
    let mut tasks = vec!["Wash", "Cook", "Study"];
    tasks.reverse();
    println!("Tasks in reverse order: {:?}", tasks);
}

Output:

Tasks in reverse order: ["Study", "Cook", "Wash"]

3) Checking for an Element

.contains(&value) checks if a vector has a particular element.

fn main() {
let fruits = vec!["Apple", "Banana", "Mango"];
println!("Contains Mango? {}", fruits.contains(&"Mango"));
println!("Contains Orange? {}", fruits.contains(&"Orange"));
}

Output:

Contains Mango? true
Contains Orange? false
  • .contains() is an easy way to check membership in a vector.

Performance Considerations

  • Vectors automatically allocate more memory as they grow, but this can be costly for large vectors.
  • If you know the number of elements in advance, you can pre-allocate memory using .with_capacity(size) and .reserve(additional).
fn main() {
// Pre-allocate memory for 5 elements
let mut items = Vec::with_capacity(5);

items.push("Pen");
items.push("Book");
items.push("Notebook");

println!("Items: {:?}", items);
println!("Capacity of vector: {}", items.capacity()); // Output: 5
}

Output:

Learn More About Rust Programming