PartialOrd

The PartialOrd trait represents the ability to define some sort of ordering between two data values, so we can say one of them is less than the other, or greater than the other, or that they're the same, or that the ordering relation does not apply to these values. That last one is the reason why this is a partial ordering.

Since they're the same is a valid result of the comparison, implementing PartialOrd requires the implemention of PartialEq.

As with PartialEq, we can derive an implementation that compares two data values of the same type, but we can also manually implement the trait to allow comparison with data of different types.

Here, we have the automatic derivation of the trait:

#[derive(PartialOrd, PartialEq)]
pub enum PartialOrdSelf {
Good,
Bad,
}

Here, we have implemented it manually to support comparison with a different data type:

pub enum PartialOrdU32 {
Good,
Bad,
}

impl PartialEq<u32> for PartialOrdU32 {
fn eq(&self, _other: &u32) -> bool {
false
}
}

impl PartialOrd<u32> for PartialOrdU32 {
fn partial_cmp(&self, _other: &u32) -> Option<Ordering> {
match self {
PartialOrdU32::Good => Some(Ordering::Greater),
PartialOrdU32::Bad => None,
}
}
}

Here, we're telling Rust that a PartialOrdU32::Good value is always greater than any u32 value, but a PartialOrdU32::Bad value does not have any relation to any u32 value at all.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.215.96