#[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));
}
Default是一个大小的特征,这意味着你 cannot convert it to a trait object .
对于上面的示例,是否有解决方法可以将大小特征存储在 Vec
(或任何其他集合)中?
最佳答案
由于对象安全规则,你不能做这样的事情。这条规则说一个方法返回具体类型本身的特征不能成为一个特征对象。原因是特征对象会知 Prop 体类型。
另外,这个 trait 没有方法(一个接受 self
的函数),所以没有必要从它创建一个 trait 对象。
查看有关此规则的更多信息 here , there在这个blog article .
另见 this question .
这条规则非常直观:您希望您的代码做什么?
#[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.
}
关于rust - 如何将大小特征插入集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51925050/