Iterating Over a Vector
Part of the Logic & Flow section of Coddy's Rust journey — lesson 11 of 66.
Now that you know how to create vectors and access individual elements, let's learn how to process every element in a vector systematically. The for loop is perfect for this task, allowing you to visit each element in sequence.
Here's the basic syntax for iterating over a vector:
let names = vec!["Alice", "Bob", "Charlie"];
for name in &names {
println!("Hello, {}!", name);
}Notice the & before names - this creates a reference to the vector, allowing you to read each element without taking ownership of the vector itself. Each iteration gives you access to one element at a time through the loop variable name.
The for loop automatically handles the bounds checking for you. Unlike manual indexing, you'll never accidentally try to access an element that doesn't exist. The loop will visit exactly as many elements as the vector contains, making it both safe and convenient.
You can use this pattern with any type of vector:
let scores = vec![85, 92, 78, 90];
for score in &scores {
println!("Score: {}", score);
}This approach is the most common and idiomatic way to process all elements in a vector when you need to read their values.
Challenge
EasyWrite a function sum_all_elements that takes a vector numbers and returns the sum of all its elements.
Use a for loop to iterate over the vector and accumulate the sum of all elements.
Parameters:
numbers(Vec<i32>): The vector of integers to sum
Returns: The sum of all elements in the vector (i32)
Cheat sheet
To iterate over a vector, use a for loop with a reference to the vector:
let names = vec!["Alice", "Bob", "Charlie"];
for name in &names {
println!("Hello, {}!", name);
}The & before the vector name creates a reference, allowing you to read each element without taking ownership. The loop automatically handles bounds checking and visits exactly as many elements as the vector contains.
This pattern works with any vector type:
let scores = vec![85, 92, 78, 90];
for score in &scores {
println!("Score: {}", score);
}Try it yourself
fn sum_all_elements(numbers: Vec<i32>) -> i32 {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together