In this MWE (link to rust-playground), I use a priority queue to store Task
. I want them to be sorted by when_to_execute
(which is the time, no other field matter). Since I am lazy, I just used the derive
attribute to implement required traits.
use chrono::prelude::*;
use chrono::Utc;
use std::collections::BinaryHeap;
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
struct Task {
when_to_execute: DateTime<Utc>,
label : String,
// foo : &Foo // Foo doesn't have required traits such as Eq etc.
}
fn main() {
let mut jm : BinaryHeap<Task> = BinaryHeap::new();
jm.push( Task{ label : "A".to_string(), when_to_execute: Utc::now()});
jm.push( Task{ label : "B".to_string(), when_to_execute: Utc::now()});
jm.push( Task{ label : "C".to_string(), when_to_execute: Utc::now()});
while ! jm.is_empty() {
println!("{:?}", jm.pop());
}
}
Output:
Some(Task { when_to_execute: 2021-12-27T15:15:58.751650790Z, label: "C" })
Some(Task { when_to_execute: 2021-12-27T15:15:58.751648633Z, label: "B" })
Some(Task { when_to_execute: 2021-12-27T15:15:58.751641679Z, label: "A" })
This is as I expected. Now, If I uncomment foo
, the code will not compile because Foo
doesn't have required traits to be in priority queue.
Is there a way I can resolve this issue without adding Eq
etc. traits to Foo
? Maybe some sort of macro that can ignore field foo
when Eq
is implemented by derive?
Update
- Looks like there is no simple solution: rust - Exclude field when deriving PartialEq - Stack Overflow