I have a question about the following code example (from this section in the book):
let v = vec![100, 32, 57];
for n_ref in &v {
// n_ref has type &i32
let n_plus_one: i32 = *n_ref + 1;
println!("{n_plus_one}");
}
After the code it says:
To read the number that n_ref refers to, we have to use the * dereference operator to get to the value in n_ref before we can add 1 to it
But that doesn't seem to be true in my testing. The following code, which is exactly the same but without the dereference, compiles and runs with no errors (which is surprising to me):
let v = vec![100, 32, 57];
for n_ref in &v {
// n_ref has type &i32
let n_plus_one: i32 = n_ref + 1;
println!("{n_plus_one}");
}
Does the book have a mistake here, or am I missing something?
It looks like mistake in the interactive version, since in the original book this part is worded differently:
To change the value that the mutable reference refers to, we have to use the * dereference operator to get to the value in i before we can use the += operator.
In this case, dereferencing is indeed necessary, since there's no impl AddAssign<i32> for &mut i32. In your case, however, it's unnecessary, since we have an implementation for reference, not only for owned value.
...actually, it's not "this part" - AddAssign is covered by the interactive version, too; it has the extra paragraph though, added in this commit. Not sure why it is here.