I was trying a problem from The Book - find the largest element in an array. I have the following solution:
fn largest<T: PartialOrd>(lis: &[T]) -> &T {
let mut larg = &lis[0];
for item in lis {
if item > larg {
larg = item;
}
}
larg
}
But to my surprise, the following works as well:
fn largest<T: PartialOrd>(lis: &[T]) -> &T {
let mut larg = &lis[0];
for item in lis {
if *item > *larg { // this line is changed
larg = item;
}
}
larg
}
I wonder why the *item and *larg work? I thought that should lead to ownership transfer. But then this is the signature of gt : fn gt(&self, other: &Rhs) -> bool
How can I pass a non-reference (*item or *larg) to gt which expects a reference?
Take another example which fails.
fn main() {
let k = 23;
let p = &k;
somefun(*p);
}
fn somefun(k: &u32) {}
What's the difference between this and PartialOrder gt with pointer deferencing?