How to convert a boxed trait into a trait reference?

前端 未结 2 1777
醉梦人生
醉梦人生 2021-01-13 05:09

I have the following code that tries to take a reference to a trait object from a boxed trait:

trait T {}

struct S {}

impl T for S {}

fn main() {
    let          


        
2条回答
  •  青春惊慌失措
    2021-01-13 05:43

    Box implements the AsRef trait, which provides the method as_ref(), so you can turn it into a reference that way:

    let trait_ref: &T = trait_box.as_ref();
    

    Normally, deref coercions mean that you don't usually need to write this out explicitly. If you pass a value of type Box to a function that takes &T, the compiler will insert the conversion for you. If you want to call one of the methods on T that takes &self, the compiler will insert the conversion for you. However, deref coercions don't apply to traits, so this won't happen for trait objects.

提交回复
热议问题