Suppose you have an array nums and your task is to increment every number in that array by one.
The first idea that might come to your mind is to write a for loop like this:
let mut nums = vec![1, 2, 3];
// Increment items:
for mut num in nums.iter().copied() {
num += 1;
}
// Print the array after:
for num in &nums {
print!("{} ", num);
}
but when you run this code, you'll be surprised to see that the output is:
1 2 3
No element in nums changed its value. How is this possible since we clearly do num += 1 for every num in nums?
Let's talk about copies:
Take a look at this code:
let number = 100;
let mut number_copy = number;
number_copy += 1;
println!("{}", number_copy); // Output: 101
println!("{}", number); // Output: 100
Although we wrote let mut number_copy = number;, this doesn't mean that number and number_copy are one and the same.
number_copy is a completely different entitity (stored at a different memory address) than number.
What we did is initialize this new number_copy entity with the value of number. That's why we say the number_copy is a copy of number.
And so number_copy += 1 will only increment number_copy and won't have any effect on number.
The loop variable is just a copy:
This is what also happens with a for loop.
Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.
This code
let mut nums = vec![1, 2, 3];
for mut num in nums.iter().copied() {
num += 1;
}
works exactly like this code:
let mut nums = vec![1, 2, 3];
let mut num = nums[0];
num += 1;
num = nums[1];
num += 1;
num = nums[2];
num += 1;
Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.
You'll see this better if we also print the value of num on each iteration.
let mut nums = vec![1, 2, 3];
for mut num in nums.iter().copied() {
num += 1;
println!("{}", num);
}
// Print the array after:
for num in &nums {
print!("{} ", num);
}
The output of this code is:
2
3
4
1 2 3
Looping over the indices:
In order to manipulate the entries of some array we have to loop over the items' indices:
let mut nums = vec![1, 2, 3];
for index in 0..nums.len() {
nums[index] += 1;
}
This code works exactly like this one:
let mut nums = vec![1, 2, 3];
let mut index = 0;
nums[index] += 1;
index += 1;
nums[index] += 1;
index += 1;
nums[index] += 1;
In this way we directly manipulate the actual entries of the list (nums[0], nums[1], etc.)
Assignment:
Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.
Free plan: 30 tutor messages. Premium is unlimited.