Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Vectors in Rust

Introduction to Vectors

In Rust, a vector is a dynamic array that can grow and shrink in size. It is defined in the standard library and provides a convenient way to store a collection of elements. Vectors are resizable, so you can easily add or remove elements as needed.

Vectors are implemented using the `Vec` type, where `T` represents the type of elements the vector will hold. This allows you to create vectors that store any type of data.

Creating Vectors

You can create a new vector using the `Vec::new()` method or by using the macro `vec![]`. Here are some examples:

Example 1: Creating a new vector
let mut numbers = Vec::new();
Example 2: Using the vec! macro
let fruits = vec!["Apple", "Banana", "Cherry"];

Adding Elements to a Vector

You can add elements to a vector using the `push` method. This method appends an element to the end of the vector:

Example: Adding elements
numbers.push(1);
numbers.push(2);
numbers.push(3);

Accessing Elements

You can access elements in a vector using indexing. Remember that indexing in Rust starts at zero. You can also use the `get` method, which returns an `Option` type that can be `Some` or `None`:

Example: Accessing elements
let first = &fruits[0];
let second = fruits.get(1);

Removing Elements

You can remove elements from a vector using the `pop` method, which removes the last element and returns it as an `Option`. Alternatively, you can use the `remove` method to remove an element at a specific index:

Example: Removing elements
let last = numbers.pop(); // Removes last element
let removed = numbers.remove(0); // Removes element at index 0

Iterating Over Vectors

You can iterate over the elements of a vector using a for loop. This allows you to access each element in sequence:

Example: Iterating over a vector
for fruit in &fruits {
    println!("{}", fruit);
}

Conclusion

Vectors are a powerful and flexible way to handle collections of data in Rust. They allow you to store a dynamic number of elements and provide useful methods for adding, accessing, and removing data. By mastering vectors, you can effectively manage collections in your Rust programs.