Question with Ord trait

    impl Ord for Person {
        fn cmp(&self, other: &Self) -> Ordering {
            self.height.cmp(&other.height)
        }
    }

    impl PartialOrd for Person {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

Above code are from trait Ord. There is a & symbol in self.height.cmp(&other.height). but not in Some(self.cmp(other)). Is that & necessary?

It is, yes: Assuming we have struct Person { height: f32 }

  • In the first part, other.height is of type f32. But you are calling f32::cmp, whose signature is cmp(&f32, &f32), so you need to add a & to give it a &f32.
  • But on the second, other is already of type &Person, so you don't need to add a & to call cmp(&Person, &Person).

To be clear, this should have nothing to do with Ord and PartialOrd in particular :slightly_smiling_face:

2 Likes

Got it. Thank you very much!

As another way to see that this is a property of the .method(...) syntax, you can write it without using that:

Ord::cmp(&self.height, &other.height)

And you'll see that removing either of the &s makes it not compile.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.