繁体   English   中英

在Rust中,如何修复错误“特性`core :: types :: Sized`没有为`Object +'a`类型实现”

[英]In Rust, how can I fix the error “the trait `core::kinds::Sized` is not implemented for the type `Object+'a`”

使用下面的代码,我得到一个“特性core::kinds::Sized没有实现类型Object+'a ”错误。 我已经删除了不需要触发错误的所有其他代码。

fn main() {
}

pub trait Object {
    fn select(&mut self);
}

pub struct Ball<'a>;

impl<'a> Object for Ball<'a> {
    fn select(&mut self) {
        // Do something
    }
}

pub struct Foo<'a> {
    foo: Vec<Object + 'a>,
}

围栏: http//is.gd/tjDxWl

完整的错误是:

<anon>:15:1: 17:2 error: the trait `core::kinds::Sized` is not implemented for the type `Object+'a`
<anon>:15 pub struct Foo<'a> {
<anon>:16     foo: Vec<Object + 'a>,
<anon>:17 }
<anon>:15:1: 17:2 note: the trait `core::kinds::Sized` must be implemented because it is required by `collections::vec::Vec`
<anon>:15 pub struct Foo<'a> {
<anon>:16     foo: Vec<Object + 'a>,
<anon>:17 }
error: aborting due to previous error
playpen: application terminated with error code 101

我对Rust很新,不知道从哪里开始。 有什么建议?

这里的根本问题是:

您想要存储对象矢量。 现在,向量是一个平面数组:每个条目都是一个接一个。 但是Object是一个特性,虽然你只为Ball实现了它,你也可以为帽子和三角形实现它。 但那些在内存中的大小可能不同! 因此,对象本身没有大小。

有两种方法可以解决这个问题:

  • 使Foo成为通用的,并且只在每个Foo中存储一种类型的Object。 我觉得这可能不是你想要的。 婴儿围栏: http//is.gd/Y0fatg
  • 间接:不是直接将对象存储在数组中,而是存储Box。 这是一个围栏链接。 http://is.gd/ORkDRC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM