Newbie question on shared references


#1

I´m trying to understand the shared reference behabior on the following functions, can someone please why do i need the for &item in list.iter() ?

fn largest(list: &[i32]) -> i32 {
    let mut largest = list[0]; // shouldn´t largest be a &i32?

    for &item in list.iter() { // if list is a &[i32] 
                               // shouldn´t item be a &32 (just item, not &item)
   // for item in list.iter() this will trow a mismatch type error on the line below
        if item > largest {
            largest = item;
        }
    }

    largest
}

Why do i need to use &item in a list thats already a &[i32] ?

That´s an example from https://doc.rust-lang.org/book/second-edition/ch10-00-generics.html


#2

The &item doesn’t actually borrow anything, but it pattern matches; so you get a &i32 which is matched against &item, so item ends up being i32.

If you would write

for item in list.iter() {

}

you had to dereference item.


#3

Immutable indexing is implemented via the std::ops::Index trait, which defines how this operation is performed. Indexing does return a reference, but that expression above desugars into:

let mut largest = *list.index(0);

Notice that there’s a dereference inserted, and since i32 is Copy, you get an i32 value back, not &i32.