I'm having difficulty understanding why this snippet from The Rust Book, Chapter 10 works:
fn largest(arr: &[i32]) -> i32 {
let mut max = arr[0];
for &i in arr.iter() {
if i > max {
max = i;
}
}
max
}
Assumption A: Using arr.iter()
will return references to the items in the array/slice/vector when iterating over it. So i
will be of type &i32
. Adding the extra &
in the definition will make it a reference to a reference, so &&i32
.
Assumption B: The IndexMut trait (used in line 2) will return a mutable reference to the item at index, so in this case a &mut i32
.
Both of these assumptions are wrong, given that both i
and max
are of type i32
. Why?
Additionally, I understand that i32
implements the Copy
-trait, but since I'm not moving ownership anywhere in this code (because everything is a reference) it shouldn't be used here, right?
Lastly, if I leave the .iter()
-call out, it works aswell. I assume that the compiler infers from the &i
-definition, that the iter()
should be used (and not iter_mut()
or into_iter()
), correct?