Borrow In Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 67 of 75.
When we write a loop in Rust, we have two main ways to work with our data: we can look at it (using &) or take it. 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;
}Cheat sheet
In Rust loops, you can either look at data (using &) or take ownership of it:
Looking at data (borrowing):
let numbers = vec![1, 2, 3, 4, 5];
for number in &numbers {
sum += number;
}
// numbers can still be used after the loopTaking ownership:
let numbers = vec![1, 2, 3, 4, 5];
for number in numbers {
sum += number;
}
// numbers cannot be used after the loopIterator methods:
// These are equivalent:
for num in numbers.iter() {}
for num in &numbers {}
// For mutation:
for num in numbers.iter_mut() { *num *= 2; }
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