Why does using Option::map to Box::new a trait object not work?

后端 未结 1 1576
我在风中等你
我在风中等你 2020-12-04 02:26
trait FooTrait {}

struct FooStruct;

impl FooTrait for FooStruct {}

fn main() {
    let maybe_struct: Option

        
1条回答
  •  情话喂你
    2020-12-04 03:03

    Box::new only works with sized types; that is, it takes a value of a sized type T and returns Box. In certain places a Box can be coerced into a Box (if T: Unsize).

    Such coercion does not happen in .map(Box::new), but does in Some(Box::new(s)); the latter is basically the same as Some(Box::new(s) as Box).

    You could create (in nightly) your own box constructor that returns boxes of unsized types like this:

    #![feature(unsize)]
    
    fn box_new_unsized(v: T) -> Box
    where
        T: ::std::marker::Unsize,
        U: ?Sized,
    {
        Box::::new(v)
    }
    

    and use it like .map(box_new_unsized). See Playground.

    0 讨论(0)
提交回复
热议问题