In Rust, how can I fix the error “the trait `core:

2019-06-27 06:34发布

With the following code, I am getting a "the trait core::kinds::Sized is not implemented for the type Object+'a" error. I've trimmed out all the other code not needed to trigger the error.

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>,
}

Playpen: http://is.gd/tjDxWl

The full error is:

<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

I'm very new to Rust and don't really know where to go from here. Any suggestions?

标签: rust
1条回答
Viruses.
2楼-- · 2019-06-27 06:52

The fundamental problem here is this:

You want to store a vector of Objects. Now, a vector is a flat array: Each entry comes after another. But Object is a trait, and while you have only implemented it for Ball, you could implement it for Hats and Triangles too. But those might be different sized in memory! So Object, on its own, doesn't have a size.

There are two ways of fixing this:

  • Make Foo generic, and only store one type of Object in each Foo. I have a feeling this may not be what you want. Playpen: http://is.gd/Y0fatg
  • Indirection: Instead of storing the Objects directly in the array, store Box instead. Here is a playpen link doing this. http://is.gd/ORkDRC
查看更多
登录 后发表回答