首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何组合``Ord::cmp ()‘中的两个cmp条件

如何组合``Ord::cmp ()‘中的两个cmp条件
EN

Stack Overflow用户
提问于 2021-04-30 14:50:54
回答 1查看 152关注 0票数 2

在从cmp()PartialEq特性实现OrdPartialEq时,我尝试将不止一个条件结合起来。像这样的东西:

代码语言:javascript
复制
self.id.cmp(&other.id) && self.age.cmp(&other.age)

下面是一个减去合并条件的工作示例:

代码语言:javascript
复制
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
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-30 14:56:04

Ord不返回布尔值,它返回一个Ordering,它可以是较少的、相等的或更大的,所以不能只在其上使用&&

Ordering有几个方法,其中之一是then (及其同伴then_with),它执行通常的“按一个字段排序,然后按另一个字段排序”操作。你的例子就变成了

代码语言:javascript
复制
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
            .then(self.age.cmp(&other.age))
    }
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67335967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档