我有一个结构:
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)