Trivial Wrapper around Box, doesn't have a size known at compile-time

I'm trying to create a wrapper around a box that manages in what thread deallocation will happen..
I'm aware of the unstable coercions (coerce_unsized, unsize) for custom smart pointers.. but it seems like that should be automatically applied here..

Is there something I am missing that would allow me to use this without having to go unstable?

#[repr(transparent)]
pub struct Wrapper<T>(Box<T>);

//works
//pub type Container = Box<dyn Event>;

//does not work
pub type Container = Wrapper<dyn Event>;

pub trait Event {
    fn foo(&mut self) -> usize;
}

pub trait Schedule {
    fn schedule(&mut self, event: Container);
}
fn main() {

}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `(dyn Event + 'static)` cannot be known at compilation time
  --> src/main.rs:13:5
   |
13 |     fn schedule(&mut self, event: Container);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `(dyn Event + 'static)`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `Wrapper`
  --> src/main.rs:2:1
   |
2  | pub struct Wrapper<T>(Box<T>);
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

One small change and this compiles:

#[repr(transparent)]
pub struct Wrapper<T>(Box<T>);
//works
//pub type Container = Box<dyn Event>;
//does not work
pub type Container = Wrapper<dyn Event>;

pub trait Event {
    fn foo(&mut self) -> usize;
}

pub trait Schedule {
    fn schedule(&mut self, event: Container);
}
fn main() {

}

Transform:

pub struct Wrapper<T>(Box<T>);

to

pub struct Wrapper<T: ?Sized>(Box<T>);

When you define a generic it is Sized by default but you don't want it.

pub struct Wrapper<T: ?Sized>(Box<T>);

@nologik You're making a Box<Box<dyn Event>> though.

2 Likes

Yep, @leudz is right

there it is! thanks @leudz and @nologik !