【发布时间】:2018-01-21 16:40:07
【问题描述】:
我有一个结构:
struct Student {
first_name: String,
last_name: String,
}
我想创建一个可以按last_name 排序的Vec<Student>。我需要实现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
}
}
如果您有很多带有明显字段要排序的结构,这可能会非常单调和重复。是否可以创建一个宏来自动实现这一点?
类似:
impl_ord!(Student, Student.last_name)
我找到了Automatically implement traits of enclosed type for Rust newtypes (tuple structs with one field),但这不是我想要的。
【问题讨论】:
-
鉴于
Student作为一种暗示特定排序顺序的数据类型没有任何意义,我会认为sort_by似乎是要走的路。
标签: rust rust-macros