如何在BinaryHeap中使用特征对象?

时间:2018-03-06 18:49:36

标签: oop rust traits trait-objects

我有以下简化代码:

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);
}

基本思想是使用(唯一的)id进行排序。

堆初始化会导致以下错误:

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特征作为&#34;接口&#34;并使用它来引发类型擦除/动态调度w.r.t泛型集合/容器 - 一种常见的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

如何解决上述问题?

0 个答案:

没有答案