我有以下简化代码:
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);
}
基本思想是使用 (unique) id
s 进行排序。
堆初始化导致以下错误:
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`
我刚刚开始尝试 Rust 并且拥有 OOP/C++/Java 背景。目的是将HasJob
特征用作“接口”并使用它来诱导类型擦除/动态调度 wrt 通用集合/容器 - 一种常见的 OOP 模式。
如果我理解正确,泛型参数BinaryHeap
具有传递给它的具体类型需要实现Ord
特征的约束。试图用所需的特征扩展原始特征,像这样......
pub trait HasJob: Ord + /*others*/
... 违反了 Rust 的对象安全保证并引发此编译器错误:
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
如何解决上述问题?