Search code examples
rusttrait-objects

How do you create a Box<dyn Trait>, or a boxed unsized value in general?


I have the following code

extern crate rand;
use rand::Rng;

pub struct Randomizer {
    rand: Box<Rng>,
}

impl Randomizer {
    fn new() -> Self {
        let mut r = Box::new(rand::thread_rng()); // works
        let mut cr = Randomizer { rand: r };
        cr
    }

    fn with_rng(rng: &Rng) -> Self {
        let mut r = Box::new(*rng); // doesn't work
        let mut cr = Randomizer { rand: r };
        cr
    }
}

fn main() {}

It complains that

error[E0277]: the trait bound `rand::Rng: std::marker::Sized` is not satisfied
  --> src/main.rs:16:21
   |
16 |         let mut r = Box::new(*rng);
   |                     ^^^^^^^^ `rand::Rng` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `rand::Rng`
   = note: required by `<std::boxed::Box<T>>::new`

I don't understand why it requires Sized on Rng when Box<T> doesn't impose this on T.


Solution

  • More about the Sized trait and bound - it's a rather special trait, which is implicitly added to every function, which is why you don't see it listed in the prototype for Box::new:

    fn new(x: T) -> Box<T>
    

    Notice that it takes x by value (or move), so you need to know how big it is to even call the function.

    In contrast, the Box type itself does not require Sized; it uses the (again special) trait bound ?Sized, which means "opt out of the default Sized bound":

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

    If you look through, there is one way to create a Box with an unsized type:

    impl<T> Box<T> where T: ?Sized
    ....
        unsafe fn from_raw(raw: *mut T) -> Box<T>
    

    so from unsafe code, you can create one from a raw pointer. From then on, all the normal things work.