Generics 如何暗示返回在Rust中使用动态分派的值?

Generics 如何暗示返回在Rust中使用动态分派的值?,generics,rust,Generics,Rust,==在2018年4月28日上午10:17编辑=== 感谢您的回答,但当我使用框跟踪您的答案时,我发现它仍然无法工作 错误信息为: error[E0038]: the trait `Entity` cannot be made into an object --> src/main.rs:20:5 | 20 | entities: Vec<Box<Entity>> | ^^^^^^^^^^^^^^^^^^^^^^^^^^ the tr

==在2018年4月28日上午10:17编辑===

感谢您的回答,但当我使用
跟踪您的答案时,我发现它仍然无法工作

错误信息为:

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`
现在我想创建一个
Vec
或一个包含
条目的数组
s:

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
}
fn创建数组(){
让mut-vec:vec=vec![];
让ea=EntryA::new();
设eb=EntryB::new();
矢量推力(ea);
矢量推力(eb);
vec
}
当我使用由
create_an_array()
创建的
Vec
时,我得到的所有元素只能显示
条目
外观,而不是详细显示子类

但是,主要的问题是,在重写函数时,Rust不仅考虑参数,还考虑返回类型(为什么这样做,Rust?!),因此我无法重写
EntryA
EntryB
中的
new()
,因为函数的返回类型与
条目的返回类型不同


如何处理动态分派问题?

您必须将您的trait对象装箱。我认为这是一个相当接近的匹配。应用第一个标记副本的技术。您还可以直接创建
new
return
Box
,或者;您的示例不需要构造函数成为trait的一部分。最好不要将新问题编辑为旧问题。请随意提出新问题,但首先。您永远不能拥有类型为
Entity
的对象,因为
Entity
是一个未大小化的类型,未大小化的类型必须始终位于某种指针后面(另请参见)。此外,您的第二个问题已经解决。
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
}