The following snippet is from the (Brown University ver.) Rust book
fn largest<T>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
I have a question about the second line.
As I understand it, the bracket operator [] automatically de-references the list
, so list[0]
is, say, an i32
. Cool.
Now I have this i32
and put a &
in front so I end up with a reference, namely &i32
. But how is this okay? Isn't this a reference to an i32
that's created inside the function? Does the i32
not go out-of-scope at the end of this function?
You are correct that the sub-expression list[0]
is of type T
. What you're missing is that there are different categories of expressions. Index operators yield a place expression which means it represents an existing memory location instead of a temporary value.
When you use &
on a place expression, you get a reference to the existing value and not to a temporary.