这个问题在这里已有答案:
===编辑于2018-04-28 10:17 AM ===
感谢您的回答,但是当我使用 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
}
}
现在我要创建 Vec
或包含 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
}
当我使用 create_an_array()
创建的 Vec
时,我得到的所有元素都可以显示 Entry
facade,而不是详细的子类 .
但是,主要的问题是,当覆盖函数时,Rust不仅会考虑参数而且还会考虑返回类型(为什么这样做,Rust?!),因此我无法覆盖 EntryA
或 EntryB
中的 new()
,因为函数具有不同的返回值类型比 Entry
特性 .
我该如何处理动态调度问题?