What does the trait PartialOrd compare?

Hi guys, I try to get the biggest element in a list, here is my two functions code :
function max:

  fn max<T:PartialOrd>(list:&[T])-> &T{
        let mut biggest = &list[0];
        for ref item in list.iter(){
           if *biggest < **item{
             biggest = *item;
           }
        }
        return biggest;
    }

function max2:

    fn max2<T:PartialOrd>(list:&[T])-> &T{
    let mut biggest = &list[0];
    for ref item in list.iter(){
       if biggest < item{
         biggest = *item;
       }
    }
    return biggest;
}

Both of them does the same work and return the same element. Does the trait PartialOrd do something for me automatically?

What you're seeing here is deref coercion in action: In max2, the dereferences are automatically inserted by the compiler, producing the same end result as max.

1 Like

Thanks a lot. It really help me.

I think it's a combination of this impl of PartialOrd for references and deref coercion. The left operand isn't touched and the compiler uses it to determine what type to expect in the right operand. The right operand is dereferenced once to turn it into the right type. I think this means that e. g. writing item > biggest instead won't work (but I haven't tested that).

Also, note that I'd consider for ref an antipattern, or at least a bit weird. I don't see any situation in which it wouldn't make sense to take ownership of the items returned by an iterator. Or rather, you take ownership anyway, even with for ref, you just then also insert an indirection with the ref foo binder. Maybe it helps save a few &item if your loop body needs references everywhere anyway, but that would still be more confusing to me than using for item in … and writing a few more &s.

3 Likes

Hi,buddy. I just test what you say. You are right. It doesn't work if I write the code like item> biggest.
When I am writing the code, the compiler suggest me to use for ref. Maybe I should follow the suggestion carefully. After I changed it as for item in ..., both item > biggest and biggest < item works well