Menu
Coddy logo textTech

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 error

Think of it like this:

  1. Using & is like looking at a photo album: you can see all the photos, but the album stays intact
  2. 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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals