如何在`Ord::cmp()`中组合两个cmp条件
我试图在实现cmp()和eq()fromOrd和PartialEqtrait时结合多个条件。看起来像这样的东西:
self.id.cmp(&other.id) && self.age.cmp(&other.age)
这是一个减去组合条件的工作示例:
use std::cmp::Ordering;
#[derive(Debug, Clone, Eq)]
pub struct Person {
pub id: u32,
pub age: u32,
}
impl Person {
pub fn new(id: u32, age: u32) -> Self {
Self {
id,
age,
}
}
}
impl Ord for Person {
fn cmp(&self, other: &Self) -> Ordering {
self.id.cmp(&other.id)
}
}
impl PartialOrd for Person {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Person {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
回答
Ord不返回布尔值,它返回一个Ordering可以是 Less、Equal 或 Greater,所以你不能只使用&&它。
Ordering有一些方法,其中之一是then(及其伴侣then_with),它执行通常的“按一个字段排序,然后按另一个字段排序”操作。你的例子然后变成
fn cmp(&self, other: &Self) -> Ordering {
self.id.cmp(&other.id)
.then(self.age.cmp(&other.age))
}