I have the following simplified code:
use std::collections::BinaryHeap;
use std::rc::Rc;
struct JobId;
struct Coord;
struct TimeStep;
pub trait HasJob {
fn id(&self) -> JobId;
fn start(&self) -> Coord;
fn end(&self) -> Coord;
fn earliest_start(&self) -> TimeStep;
fn latest_finish(&self) -> TimeStep;
}
type JobPtr = Rc<HasJob>;
// a concrete class that implements the above trait
// and other basic traits like Eq, Hash, Ord, etc
pub struct Job {}
// another class that implements the HasJob trait
pub struct JobPrime {}
fn main() {
// this line raises a compiler error
let heap: BinaryHeap<JobPtr> = BinaryHeap::with_capacity(10);
}
The basic idea is to use the (unique) id
s for ordering.
The heap initialization causes the following error:
error[E0277]: the trait bound `HasJob: std::cmp::Ord` is not satisfied
--> src/main.rs:24:36
|
24 | let heap: BinaryHeap<JobPtr> = BinaryHeap::with_capacity(10);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::cmp::Ord` is not implemented for `HasJob`
|
= note: required because of the requirements on the impl of `std::cmp::Ord` for `std::rc::Rc<HasJob>`
= note: required by `<std::collections::BinaryHeap<T>>::with_capacity`
I've just started trying my hand at Rust and have an OOP/C++/Java background. The intention is to use the HasJob
trait as an "interface" and use that to induce type erasure/dynamic dispatch w.r.t generic collections/containers - A common OOP pattern.
If I understand correctly, the generic parameter of BinaryHeap
has the constraint that the concrete type passed to it needs to implement the Ord
trait. Attempting to extend the original trait with required trait like so...
pub trait HasJob: Ord + /*others*/
... violates Rust's object safety guarantee and raises this compiler error:
error[E0038]: the trait `HasJob` cannot be made into an object
--> src/main.rs:16:22
|
16 | type JobPtr = Rc<HasJob>;
| ^^^^^^ the trait `HasJob` cannot be made into an object
|
= note: the trait cannot use `Self` as a type parameter in the supertraits or where-clauses
How do I get around the above issue?