Welcome to the third lesson in our Rust series! Today, we'll dive into iterating over vectors ā a fundamental concept in Rust programming. Let's get started! š
In Rust, a Vec (short for vector) is a dynamically-sized array that can hold items of the same type. Vectors are a common data structure in programming, and Rust's implementation makes it easy to work with them.
To iterate over a vector, we can use the iter() method, which returns an iterator for the vector. An iterator is a sequence of items that can be accessed one by one.
Here's a simple example:
let numbers = vec![1, 2, 3, 4, 5];
for number in numbers.iter() {
println!("{}", number);
}In this example, we create a vector of integers named numbers. The iter() method is called on the vector, which returns an iterator. We then use a for loop to iterate over the iterator and print each number.
š Note: The iter() method returns an iterator that doesn't modify the original vector. If you need to modify the vector while iterating, use the iter_mut() method instead.
for loop š”The for loop is used to iterate over collections such as vectors. Here's the basic structure of a for loop:
for item in collection {
// code to execute for each item
}When iterating over a collection, you can access both the index and value of an item if needed. To access the index, use the enumerate() method on the collection before the iter() method.
let numbers = vec![1, 2, 3, 4, 5];
for (index, number) in numbers.iter().enumerate() {
println!("Index: {}, Number: {}", index, number);
}In this example, we use the enumerate() method to get both the index and value of each item in the numbers vector.
You can also use the map() and filter() methods to manipulate the items while iterating.
Here's an example of iterating and doubling the numbers in a vector:
let numbers = vec![1, 2, 3, 4, 5];
let doubled_numbers = numbers.iter().map(|number| number * 2).collect::<Vec<_>>();
println!("{:?}", doubled_numbers);In this example, we use the map() method to double each number and then collect the results into a new vector.
Which method is used to iterate over a vector in Rust?
Let's say you're building a simple inventory system for a game, and you have a vector of items. You can use iterating to display each item's name and quantity.
let items = vec![
("Sword", 5),
("Armor", 3),
("Bow", 7),
];
for (item_name, quantity) in items.iter() {
println!("Item: {}, Quantity: {}", item_name, quantity);
}In this example, we have a vector of tuples, where each tuple contains an item's name and quantity. We then iterate over the vector and print each item's name and quantity.
Understanding how to iterate over vectors is crucial in working with data collections in Rust. With the iter(), map(), and filter() methods, you can manipulate and process data efficiently.
In the next lesson, we'll explore more advanced topics in Rust. Until then, keep practicing and enjoy the journey of learning Rust! š”