Is there any way to convert Box> to Box>?

后端 未结 2 1957
眼角桃花
眼角桃花 2021-01-21 14:49

Consider such code:

trait Foo {
    fn foo(&self);
}

fn consume_func(b: Box>) {
    unimplemented!();
}

fn produce_func() -> Box<         


        
相关标签:
2条回答
  • 2021-01-21 15:04

    Here's one way to do it: dereference b ("un-boxing" it to a Box<Foo + Send>), then wrap it up immediately in another Box<T>, allowing the compiler to infer the correct T (in this case Box<Foo>).

    consume_func(Box::new(*b));
    

    This works because Box<Foo + Send> can be automatically coerced to Box<Foo>, but Box<Box<Foo + Send>> cannot be coerced to Box<Box<Foo>>.

    0 讨论(0)
  • 2021-01-21 15:07

    Although you've stated you cannot change consume_func, others with similar issues can change it to accept a generic:

    fn consume_func<F: Foo + ?Sized>(b: Box<Box<F>>) {
        unimplemented!();
    }
    
    0 讨论(0)
提交回复
热议问题