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:

  1. What are Vectors?
  2. Creating Vectors
  3. Accessing Elements
  4. Modifying Vectors
  5. Iterating Over Vectors
  6. Common Vector Methods
  7. 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

let v = vec![1, 2, 3];
println!("{:?}", v); // Output: [1, 2, 3]

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 an Option<&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

let mut v = vec![1, 2, 3];
v.push(4);
println!("{:?}", v); // Output: [1, 2, 3, 4]

Removing Elements

let mut v = vec![1, 2, 3, 4];
v.pop();
println!("{:?}", v); // Output: [1, 2, 3]

Changing Elements

let mut v = vec![1, 2, 3];
v[1] = 10;
println!("{:?}", v); // Output: [1, 10, 3]

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

let v = vec![1, 2, 3];
for i in &v {
    println!("{}", i);
}

Using Iterators

let v = vec![1, 2, 3];
for i in v.iter() {
    println!("{}", i);
}

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

  1. Create a vector of integers.
  2. Add the numbers 1 through 5 to the vector.
  3. Change the third element to 10.
  4. Remove the last element.
  5. 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

  1. Create a vector of integers.
  2. Add the numbers 1 through 5 to the vector.
  3. Iterate over the vector and calculate the sum of its elements.
  4. 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.

Rust Programming Course

Module 1: Introduction to Rust

Module 2: Basic Concepts

Module 3: Ownership and Borrowing

Module 4: Structs and Enums

Module 5: Collections

Module 6: Error Handling

Module 7: Advanced Concepts

Module 8: Concurrency

Module 9: Advanced Features

Module 10: Project and Best Practices

© Copyright 2024. All rights reserved