From playing with the compiler, I can see that Rust takes the variable item
here as type &T
:
fn largest<T>(list: &[T]) -> &T
where T: PartialOrd {
let mut largest = &(list[0]);
for item in list {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is: {}", result);
}
Why? Of course that's what I want, but I didn't specify it. Does Rust just automatically take items as references when taking from references to containers?
Also, why does the code still compile if I change line 7 as follows:
for item in list {
if item > largest {
largest = &item;
}
}
Is Rust automatically dereferencing the return value once match the type signature I declared for largest
? Without even outputting a warning?
How can I assign &x
, where x: &T
, to another variable y
where y: &T
. Certainly I should get a type mismatch: &&T
does not match &T
?
I've tried reading the documentation but it seems to dodge the question about what's actually going on.
I know Rust does auto reference/dereference on method calls, which makes sense as the type of the receiver is specified explicitly (and who really wants to read something like (&receiver).method(args)
in code?). But auto reference/dereference on variable assignments? Surely that can't be what's happening?