0

I have the following code:

  • A struct containing a vector of things of a specific trait
  • This struct needs to have #[derive(Clone)] because it will become a member of another struct, which is already marked as #[derive(Clone)]

I naively started with the following code:

pub trait Foo : Clone
{
    fn bar(&self);
}

#[derive(Clone)]
pub struct Baz {
    qux: Vec<Box<dyn Foo>>
}

And run into the following error. Tried to add Sized, but never got to a working state.

error[E0038]: the trait `Foo` cannot be made into an object
 --> src/lib.rs:8:18
  |
8 |     qux: Vec<Box<dyn Foo>>
  |                  ^^^^^^^ `Foo` cannot be made into an object
  |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
 --> src/lib.rs:1:17
  |
1 | pub trait Foo : Clone
  |           ---   ^^^^^ ...because it requires `Self: Sized`
  |           |
  |           this trait cannot be made into an object...

For more information about this error, try `rustc --explain E0038`.

Tried the same thing from another angle

pub trait Foo {
    fn bar(&self);
}

#[derive(Clone)]
pub struct Baz<T: Foo >
{
    qux: Vec<T>
}

#[tokio::main]
async fn main() {
    let a = Baz::<dyn Foo> {
        qux: vec! []
    };
}

And run into a very similar problem around Sized.

How can I achieve something like that? I am pretty sure that I am missing (don't know) some features of Rust that solve whole this problem.

I believe Vec<Box> is unbelievably common. The thing which I am trying to figure out is how to marry it with Clone.

Victor Ronin
  • 21,988
  • 17
  • 90
  • 178

0 Answers0