如何将大小的特征插入到集合中

hel*_*low 3 rust

操场

#[derive(Default)]
struct Bar;

#[derive(Default)]
struct Baz;

fn main() {
    let mut vec = Vec::<Box<dyn Default>>::new();
//                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::default::Default` cannot be made into an object
    vec.push(Box::new(Bar));
    vec.push(Box::new(Baz));
}
Run Code Online (Sandbox Code Playgroud)

默认值是一个大小的Trait,这意味着您无法将其转换为特征对象.

对于上面的示例,是否有解决方法,以便我可以在Vec(或任何其他集合)中存储大小的特征?

Fre*_*ios 5

由于对象安全规则,你不能做这样的事情.该规则表示方法返回具体类型本身的特征不能成为特征对象.原因是特质对象已经知道具体类型.

此外,这个特性没有方法(一个需要的函数self),因此没有必要从中创建一个特征对象.

查看更多有关这条规则在这里,这个在博客文章.

另见这个问题.


此规则非常直观:您希望代码执行什么操作?

#[derive(Default)]
struct Bar;

#[derive(Default)]
struct Baz;

fn main() {
    let mut vec = Vec::<Box<dyn Default>>::new();
    vec.push(Box::new(Bar));
    vec.push(Box::new(Baz));

    vec.first().unwrap()::new();
    // Whatever the syntax should be, what do you expect this to return?
    // This type cannot be know at compile time.
}
Run Code Online (Sandbox Code Playgroud)