PartialEq

The PartialEq trait represents the ability to compare the data value with another one to determine whether they are equal. It does not imply that a value is considered equal to itself, however.

The PartialEq trait is used by the compiler to implement the == comparison operation.

Floating point numbers are the classic example of a data type that has PartialEq, because the floating point representation of a NaN or Not a Number value is not considered equal to itself.

Deriving PartialEq looks like this:

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

However, that derivation only compares two PartialEqSelf data values. If we want to enable an equality comparison with data values of other types, we need to implement the trait manually.

Here, we have a manual implementation of the trait, enabling comparison with the u32 data type:

pub enum PartialEqU32 {
Good,
Bad,
}

impl PartialEq<u32> for PartialEqU32 {
fn eq(&self, other: &u32) -> bool {
match self {
PartialEqU32::Good => other % 2 == 0,
PartialEqU32::Bad => other % 2 == 1,
}
}
}

Here, we've arranged for the PartialEqU32::Good value to compare as equal to even number u32s, and PartialEqU32::Bad to compare equal to odd number u32.

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

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