How do you create a Box when T is a trait-object?

后端 未结 3 1896
悲哀的现实
悲哀的现实 2021-01-14 05:42

I have the following code

extern crate rand;
use rand::Rng;

pub struct Randomizer {
    rand: Box,
}

impl Randomizer {
    fn new() -> Self {         


        
3条回答
  •  滥情空心
    2021-01-14 06:33

    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
    

    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 where T: ?Sized(_);
    

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

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

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

提交回复
热议问题