Say I have the following struct:
struct Node {
location: Location,
price: f32
}
And now, I want to store a number of Node
s in a BinaryHeap.
let heap: BinaryHeap<Node> = BinaryHeap::new();
However, since I have not implemented Ord
for Node
, the above declaration would err.
Problem
There are at least two ways to implement the cmp
function for Node
:
// compare by price
fn cmp(&self, other: &Self) -> Ordering {
other.price.cmp(&self.price)
}
// or compare by distance (not sure if I can add an extra argument, but let's assume we can)
fn cmp(&self, other: &Self, source_node: &Node) -> Ordering {
other.distance_to(source_node).cmp(&self.distance_to(source_node))
}
And I want to give user the ability to pass in their own custom cmp
function, and use that for BinaryHeap ordering.
In Java, you can pass in a custom comparator function for PriorityQueue: see here for an example. But it seems like BinaryHeap in rust doesn't really have that ability.
Are there any workarounds to achieve this?