I'm writing a priority queue, and I want to allow a custom comparator, but also provide a default option.
pub struct PriorityQueue<T: PartialOrd, F: Fn(&T, &T) -> bool> {
heap: Vec<T>,
compare: F,
}
impl<T: PartialOrd, F: Fn(&T, &T) -> bool> PriorityQueue<T, F> {
pub fn new(data: Vec<T>) -> Self {
Self::with_ordering(data, |a, b| a < b)
}
pub fn with_ordering(data: Vec<T>, ordering: F) -> Self {
let mut queue = Self {
heap: data,
compare: ordering,
};
queue.heapify();
queue
}
}
Rust doesn't like this though:
error[E0308]: mismatched types
--> src/lib.rs:8:35
|
6 | impl<T: PartialOrd, F: Fn(&T, &T) -> bool> PriorityQueue<T, F> {
| - this type parameter
7 | pub fn new(data: Vec<T>) -> Self {
8 | Self::with_ordering(data, |a, b| a < b)
| ^^^^^^^^^^^^ expected type parameter `F`, found closure
|
= note: expected type parameter `F`
found closure `[closure@src/lib.rs:8:35: 8:47]`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`
For more information about this error, try `rustc --explain E0308`.
This error makes sense, but I don't really know how to work around it. My first thought was to create a second impl
block where I specified that F
is the type of |a, b| a < b
, but I don't know what syntax I could use to specify that. What can I do here?