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
Creating Vectors
You can create a new vector using the `Vec::new()` method or by using the macro `vec![]`. Here are some examples:
let mut numbers = Vec::new();
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:
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`:
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:
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:
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.