在从 Ord
和 PartialEq 实现
特征。看起来像这样的东西:cmp()
和 eq()
时,我试图组合多个条件
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
不返回 bool 值,它返回 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))
}
关于rust - 如何结合 `Ord::cmp()`中的两个cmp条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67335967/