小编aon*_*emd的帖子

如何在`Ord::cmp()`中组合两个cmp条件

我试图在实现cmp()eq()fromOrdPartialEqtrait时结合多个条件。看起来像这样的东西:

self.id.cmp(&other.id) && self.age.cmp(&other.age)
Run Code Online (Sandbox Code Playgroud)

这是一个减去组合条件的工作示例:

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 …
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
1
解决办法
42
查看次数

标签 统计

rust ×1