比较
这些 trait 支持在值之间进行比较。对于包含实现这些 trait 的字段,可以派生所有这些 trait。
PartialEq and Eq
PartialEq 指部分等价关系,其中包含必需的方法 eq 和提供的方法 ne。== 和 != 运算符会调用这些方法。
1. struct Key {
2. id: u32,
3. metadata: Option<String>,
4. }
5. impl PartialEq for Key {
6. fn eq(&self, other: &Self) -> bool {
7. self.id == other.id
8. }
9. }
Eq is a full equivalence relation (reflexive, symmetric, and transitive) and implies PartialEq. Functions that require full equivalence will use Eq as a trait bound.
PartialOrd and Ord
PartialOrd 定义了使用 partial_cmp 方法的部分排序。它用于实现 <、<=、>= 和 > 运算符。
1. use std::cmp::Ordering;
2. #[derive(Eq, PartialEq)]
3. struct Citation {
4. author: String,
5. year: u32,
6. }
7. impl PartialOrd for Citation {
8. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
9. match self.author.partial_cmp(&other.author) {
10. Some(Ordering::Equal) => self.year.partial_cmp(&other.year),
11. author_ord => author_ord,
12. }
13. }
14. }
Ord 是总排序,其中 cmp 返回 Ordering。
This slide should take about 10 minutes.
PartialEq 可以在不同类型之间实现,但 Eq 不能,因为它具有自反性:
1. struct Key {
2. id: u32,
3. metadata: Option<String>,
4. }
5. impl PartialEq<u32> for Key {
6. fn eq(&self, other: &u32) -> bool {
7. self.id == *other
8. }
9. }
在实践中,派生这些 trait 很常见,但很少会实现它们。
