2023-11-29 10:39:24 -05:00
|
|
|
---
|
2024-06-07 09:11:57 -07:00
|
|
|
minutes: 5
|
2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# Comparisons
|
|
|
|
|
|
|
|
These traits support comparisons between values. All traits can be derived for
|
|
|
|
types containing fields that implement these traits.
|
|
|
|
|
|
|
|
## `PartialEq` and `Eq`
|
|
|
|
|
|
|
|
`PartialEq` is a partial equivalence relation, with required method `eq` and
|
|
|
|
provided method `ne`. The `==` and `!=` operators will call these methods.
|
|
|
|
|
|
|
|
```rust,editable
|
2023-12-31 00:15:07 +01:00
|
|
|
struct Key {
|
|
|
|
id: u32,
|
|
|
|
metadata: Option<String>,
|
|
|
|
}
|
2023-11-29 10:39:24 -05:00
|
|
|
impl PartialEq for Key {
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
self.id == other.id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
`Eq` is a full equivalence relation (reflexive, symmetric, and transitive) and
|
2023-12-31 00:15:07 +01:00
|
|
|
implies `PartialEq`. Functions that require full equivalence will use `Eq` as a
|
|
|
|
trait bound.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
## `PartialOrd` and `Ord`
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
`PartialOrd` defines a partial ordering, with a `partial_cmp` method. It is used
|
|
|
|
to implement the `<`, `<=`, `>=`, and `>` operators.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
use std::cmp::Ordering;
|
|
|
|
#[derive(Eq, PartialEq)]
|
2023-12-31 00:15:07 +01:00
|
|
|
struct Citation {
|
|
|
|
author: String,
|
|
|
|
year: u32,
|
|
|
|
}
|
2023-11-29 10:39:24 -05:00
|
|
|
impl PartialOrd for Citation {
|
|
|
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
|
|
|
match self.author.partial_cmp(&other.author) {
|
|
|
|
Some(Ordering::Equal) => self.year.partial_cmp(&other.year),
|
|
|
|
author_ord => author_ord,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
`Ord` is a total ordering, with `cmp` returning `Ordering`.
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
`PartialEq` can be implemented between different types, but `Eq` cannot, because
|
|
|
|
it is reflexive:
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
```rust,editable
|
2023-12-31 00:15:07 +01:00
|
|
|
struct Key {
|
|
|
|
id: u32,
|
|
|
|
metadata: Option<String>,
|
|
|
|
}
|
2023-11-29 10:39:24 -05:00
|
|
|
impl PartialEq<u32> for Key {
|
|
|
|
fn eq(&self, other: &u32) -> bool {
|
|
|
|
self.id == *other
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
In practice, it's common to derive these traits, but uncommon to implement them.
|
|
|
|
|
|
|
|
</details>
|