Trying to understand how &
works in a rust for..in
loop...
For example let's say we have something simple like a find largest value function which takes a slice of i32
's and returns the largest value.
fn largest(list: &[i32]) -> i32 {
let mut largest = list[0];
for item in list {
if *item > largest {
largest = *item;
}
}
largest
}
In the scenario given above item
will be an &i32
which makes sense to me. We borrow a slice of i32
's and as a result the item
would also be a reference to the individual item in the slice. At this point we can dereference the value of item
with *
which is what I assume how a pointer based language would work.
But now if we alter this slightly below...
fn largest(list: &[i32]) -> i32 {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
If we put an &
in front of item
this changes item
within the for..in
into an i32
... Why? In my mind this is completely counterintuitive to how I would have imagined it to work. This to me says, "Give me an address/reference to item
"... Which in itself would already be a reference. So then how does item
get dereferenced? Is this just a quirk with rust or am I fundamentally missing something here.