【发布时间】:2015-07-23 15:52:07
【问题描述】:
对不起,如果这看起来微不足道,但我正在尝试做一个简单的操作,但我很难做到。我只想拥有两个特征对象,其中一个具有一个包含一堆其他对象的 Vector。
trait MetaClass {
fn new() -> Self;
fn add(&self, subtrait: Box<SubClass>);
}
struct MetaStruct {
elems: Vec<Box<SubClass>>,
}
impl MetaClass for MetaStruct{
fn new() -> MetaStruct {
MetaStruct{
elems: Vec::new(),
}
}
fn add(&self, subtrait: Box<SubClass>){
// if I reformulate the above to 'fn add(&self, subtrait: SubClass){'
// and use the below I get the trait `core::marker::Sized` is not implemented for the type `SubClass`
//self.elems.push(Box::new(subtrait));
self.elems.push(subtrait);
}
}
trait SubClass{
fn new() -> Self;
}
struct MySubClass {
data: i32,
}
impl SubClass for MySubClass {
fn new() -> MySubClass{
MySubClass{
data: 10,
}
}
}
fn main(){
let mut meta = Box::new(MetaStruct::new());
// ideally I just want to do meta.add(MySubClass::new()) but as mentioned above that has some sizing issues :'(
meta.add(Box::new(MySubClass::new()));
}
我得到的错误是:
<anon>:45:11: 45:38 error: cannot convert to a trait object because trait `SubClass` is not object-safe [E0038]
<anon>:45 meta.add(Box::new(MySubClass::new()));
^~~~~~~~~~~~~~~~~~~~~~~~~~~
这里是 rust play 的链接:http://is.gd/pjLheJ
我也尝试了以下方法,但得到了同样的错误:
meta.add(Box::new(MySubClass::new()) as Box<SubClass>);
理想情况下,如果有一种方法可以使用 Rust 的静态调度来做到这一点,那将是理想的,但我也可以使用动态调度。在每种情况下,我认为让 MetaClass 实际上拥有子类的对象是有意义的,所以我不想传递对它的引用,而是传递整个对象本身。
【问题讨论】:
标签: rust