Understanding Rust's Vec: A Comprehensive Guide

Understanding Rust's Vec: A Comprehensive Guide

Introduction to Vec

A Vec: A Vec<T> (vector) is a resizable array type provided by Rust's standard library. It allows you to store multiple values of the same type in a dynamic array that can grow and shrink in size.

Key Concepts

Creating a Vec

Another way is to use the vec! macro:

let v = vec![1, 2, 3];

You can create a new, empty vector using:

let mut v: Vec = Vec::new();

Adding Elements

Use the push method to add elements to the vector:

v.push(4);

Accessing Elements

Use the get method for safe access that returns an Option:

let second = v.get(1); // Returns Some(&2) or None if out of bounds

You can access elements using indexing:

let first = &v[0]; // Get the first element

Iterating Over a Vec

You can loop through elements using a for loop:

for value in &v {
    println!("{}", value);
}

Removing Elements

Use the pop method to remove the last element:

let last = v.pop(); // Removes and returns the last element

Slicing a Vec

You can create a slice of a vector to work with a portion of its elements:

let slice = &v[0..2]; // Gets a slice containing the first two elements

Capacity and Performance

  • Vectors have a capacity that determines how many elements they can hold without reallocating.

You can check the current capacity with:

let cap = v.capacity();

Example Code

Here’s a complete example demonstrating the use of a Vec:

fn main() {
    let mut numbers = vec![1, 2, 3];
    
    numbers.push(4); // Add an element
    println!("{:?}", numbers); // Output: [1, 2, 3, 4]

    let second = numbers.get(1).unwrap(); // Access the second element
    println!("The second number is: {}", second); // Output: 2

    for num in &numbers {
        println!("{}", num); // Output: 1, 2, 3, 4
    }

    numbers.pop(); // Remove the last element
    println!("{:?}", numbers); // Output: [1, 2, 3]
}

Conclusion

Vec is a powerful and flexible way to manage collections of data in Rust. It provides various methods for manipulating data, including adding, accessing, iterating, and removing elements. By understanding these basic operations and concepts, beginners can effectively utilize vectors in their Rust programs.