小编Haf*_*fix的帖子

是否可以通过委托给结构成员来创建一个实现 Ord 的宏?

我有一个结构:

struct Student {
    first_name: String,
    last_name: String,
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个Vec<Student>可以按last_name. 我需要实现Ord,PartialOrd并且PartialEq:

use std::cmp::Ordering;

impl Ord for Student {
    fn cmp(&self, other: &Student) -> Ordering {
        self.last_name.cmp(&other.last_name)
    }
}

impl PartialOrd for Student {
    fn partial_cmp(&self, other: &Student) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Student {
    fn eq(&self, other: &Student) -> bool {
        self.last_name == other.last_name
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您有很多结构体都有明显的字段可供排序,这可能会非常单调和重复。是否可以创建一个宏来自动实现这一点?

就像是:

impl_ord!(Student, Student.last_name)
Run Code Online (Sandbox Code Playgroud)

我发现自动实现 Rust newtypes (tuple structs …

rust rust-macros

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

标签 统计

rust ×1

rust-macros ×1