Newbie question on shared references


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;


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

That´s an example from

[solved] Largest item in a possibly empty vector (without early return)

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.

[solved] Largest item in a possibly empty vector (without early return)

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.