Mutable Iteration
Part of the Logic & Flow section of Coddy's Rust journey — lesson 12 of 66.
Sometimes you need to do more than just read vector elements - you need to modify them. While the previous lesson showed how to iterate and read values, this lesson teaches you how to change the elements during iteration using mutable references.
To modify elements while iterating, you need to use &mut instead of & in your for loop:
let mut numbers = vec![1, 2, 3, 4];
for number in &mut numbers {
*number = *number * 2;
}The &mut numbers creates a mutable reference to the vector, and each iteration gives you a mutable reference to an individual element. The * operator (called the dereference operator) is used to access and modify the actual value that the reference points to.
This pattern is incredibly useful for transforming data in place. Instead of creating a new vector with modified values, you can efficiently update the existing one. The vector must be declared as mut for this to work, since you're changing its contents.
After the loop above, numbers would contain [2, 4, 6, 8] - each original value doubled in place.
Challenge
EasyWrite a function add_ten_to_all that takes a mutable vector numbers and adds 10 to each element in place, then returns the modified vector.
Use mutable iteration with &mut to modify each element directly. Remember to use the dereference operator * to access and modify the actual values.
Parameters:
numbers(Vec<i32>): A mutable vector of integers to modify
Returns: The modified vector with 10 added to each element (Vec<i32>)
Cheat sheet
To modify vector elements during iteration, use mutable references with &mut:
let mut numbers = vec![1, 2, 3, 4];
for number in &mut numbers {
*number = *number * 2;
}Key points:
&mut numberscreates a mutable reference to the vector- Each iteration provides a mutable reference to an individual element
- The
*operator (dereference operator) accesses and modifies the actual value - The vector must be declared as
mutto allow modification
This pattern allows you to transform data in place efficiently without creating a new vector.
Try it yourself
fn add_ten_to_all(numbers: Vec<i32>) -> Vec<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