rust - 如何结合 `Ord::cmp()`中的两个cmp条件

标签 rust

在从 OrdPartialEq 实现 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/

相关文章:

json - 如何将所有字段都是默认值的类型反序列化为 None ?

rust - 如何为结构的可变引用中的字段换入新值?

rust - 切片中的不可变引用是如何更新的?为什么它不改变引用变量的值?

rust - 如何从 Visual Studio Code 启动 Rust 应用程序?

rust - 为什么 return 语句后面的分号是可选的?

rust - 为什么创建对取消引用的可变引用的可变引用有效?

string - 如何 "interpret"转义字符串中的字符?

opengl - 如何反转3D look_at函数?

rust - "cannot infer type for type f64"和 "consider giving ... a type"错误消息

rust - 在 Rust 中别名闭包类型,但编译器要求生命周期说明符