首页 > 解决方案 > 如何暗示返回一个在 Rust 中使用动态调度的值?

问题描述

=== 编辑于 2018-04-28 10:17AM ===

感谢您的回答,但是当我使用 遵循您的回答时Box<>,我发现它仍然无法正常工作。

https://play.rust-lang.org/?gist=211845d953cd9012f6f214aa5d81332d&version=stable&mode=debug

错误信息是:

error[E0038]: the trait `Entity` cannot be made into an object
  --> src/main.rs:20:5
   |
20 |     entities: Vec<Box<Entity>>
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Entity` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

所以我想知道是cannot be made into an object什么?我该如何解决这个问题?

===原始答案===
我想用普通类实现像Java的接口/抽象类这样的层次结构:

trait Entry {
    fn new() -> Entry;
}

struct EntryA {}
impl Entry for EntryA {
    fn new() -> EntryA {
        // I want to return EntryA rather Entry here, just like dynamic dispatch in Java
    }
}

struct EntryB {}
impl Entry for EntryB {
    fn new() -> EntryB {
        // Another Entry struct
    }
}

现在我想创建一个或一个包含sVec的数组:Entry

fn create_an_array() -> [Something to write here] {
    let mut vec: Vec<Entry> = vec![];
    let ea = EntryA::new();
    let eb = EntryB::new();
    vec.push(ea);
    vec.push(eb);
    vec
}

当我使用Veccreated bycreate_an_array()时,我得到的所有元素都只能显示Entry外观,而不是详细显示子类。

然而,主要的问题是,当重写函数时,Rust 不仅考虑参数,还考虑返回类型(Rust 你为什么这样做?!),所以我不能重写或者因为函数的返回类型new()与特征。EntryAEntryBEntry

如何处理动态调度的问题?

标签: genericsrust

解决方案


推荐阅读