Borrow In Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 67 of 75.
In Rust, every value has an owner, and when you use a value in a loop, Rust needs to know whether you want to borrow it (just look at it temporarily) or take ownership of it (consume it).
This matters because if a loop takes ownership of your data, you can no longer use that data after the loop ends. Understanding this distinction is the key to writing loops correctly in Rust.
For example, consider the following data:
let numbers = vec![1, 2, 3, 4, 5];
let mut sum = 0;Method 1: Looking at the data (using &):
for number in &numbers {
sum += number;
}
println!("I can use it here: {:?}", numbers);Method 2: Taking the data (without &):
for number in numbers {
sum += number;
}
// println!("Can't use {:?} anymore!", numbers);
// This would cause an errorThink of it like this:
- Using
&is like looking at a photo album: you can see all the photos, but the album stays intact - Not using
&is like taking the photos out: you can use them, but the album will be empty afterward
Now this style:
for num in numbers.iter() {}Is similar to this:
for num in &numbers {}And a mutation loop:
for num in numbers.iter_mut() {
*num *= 2;
}Can also be written this way:
for num in &mut numbers {
*num *= 2;
}Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input