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

后端 未结 2 1961
眼角桃花
眼角桃花 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), then wrap it up immediately in another Box, allowing the compiler to infer the correct T (in this case Box).

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

    This works because Box can be automatically coerced to Box, but Box> cannot be coerced to Box>.

提交回复
热议问题