Vectors in Rust are a dynamic array type provided by the standard library. They are one of the most commonly used collections in Rust due to their flexibility and ease of use. In this section, we will cover the following topics:
- What are Vectors?
- Creating Vectors
- Accessing Elements
- Modifying Vectors
- Iterating Over Vectors
- Common Vector Methods
- Practical Exercises
What are Vectors?
Vectors (Vec<T>
) are resizable arrays that can hold multiple values of the same type. They are stored on the heap, which allows them to grow or shrink in size dynamically.
Creating Vectors
You can create vectors in several ways:
Using Vec::new
let mut v: Vec<i32> = Vec::new(); v.push(1); v.push(2); v.push(3); println!("{:?}", v); // Output: [1, 2, 3]
Using the vec!
Macro
Explanation
Vec::new()
creates an empty vector.vec!
macro creates a vector with initial values.
Accessing Elements
You can access elements in a vector using indexing or the get
method.
Using Indexing
let v = vec![1, 2, 3]; let third = v[2]; println!("The third element is {}", third); // Output: The third element is 3
Using the get
Method
let v = vec![1, 2, 3]; match v.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), }
Explanation
- Indexing directly accesses the element but will panic if the index is out of bounds.
get
method returns anOption<&T>
, which is safer as it handles out-of-bounds access gracefully.
Modifying Vectors
You can modify vectors by adding, removing, or changing elements.
Adding Elements
Removing Elements
Changing Elements
Explanation
push
adds an element to the end of the vector.pop
removes the last element and returns it.- Indexing can be used to change elements directly.
Iterating Over Vectors
You can iterate over vectors using a for
loop or iterators.
Using a for
Loop
Using Iterators
Explanation
for
loop with&v
borrows each element.iter
method returns an iterator over the vector.
Common Vector Methods
Here are some commonly used methods for vectors:
Method | Description |
---|---|
push |
Adds an element to the end of the vector. |
pop |
Removes the last element and returns it. |
len |
Returns the number of elements in the vector. |
is_empty |
Returns true if the vector is empty. |
insert |
Inserts an element at a specified index. |
remove |
Removes and returns the element at a specified index. |
clear |
Removes all elements from the vector. |
contains |
Checks if the vector contains a specified value. |
Practical Exercises
Exercise 1: Create and Modify a Vector
- Create a vector of integers.
- Add the numbers 1 through 5 to the vector.
- Change the third element to 10.
- Remove the last element.
- Print the vector.
Solution
fn main() { let mut v = Vec::new(); for i in 1..=5 { v.push(i); } v[2] = 10; v.pop(); println!("{:?}", v); // Output: [1, 2, 10, 4] }
Exercise 2: Iterate and Sum Elements
- Create a vector of integers.
- Add the numbers 1 through 5 to the vector.
- Iterate over the vector and calculate the sum of its elements.
- Print the sum.
Solution
fn main() { let v = vec![1, 2, 3, 4, 5]; let sum: i32 = v.iter().sum(); println!("The sum is {}", sum); // Output: The sum is 15 }
Conclusion
In this section, we covered the basics of vectors in Rust, including how to create, access, modify, and iterate over them. We also explored some common methods and provided practical exercises to reinforce the concepts. Understanding vectors is crucial as they are a fundamental part of Rust's collection types and are widely used in various applications. In the next section, we will delve into strings, another essential collection type in Rust.