Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 struct_box: Box<S> = Box::new(S {});
    let struct_ref: &S = &struct_box;

    let trait_box: Box<T> = Box::new(S {});
    let trait_ref: &T = &trait_box;
}

The compiler returns the following error:

error[E0277]: the trait bound `std::boxed::Box<T>: T` is not satisfied
  --> src/main.rs:12:25
   |
12 |     let trait_ref: &T = &trait_box;
   |                         ^^^^^^^^^^ the trait `T` is not implemented for `std::boxed::Box<T>`
   |
   = note: required for the cast to the object type `T`

How do I properly borrow &T from Box<T>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
913 views
Welcome To Ask or Share your Answers For Others

1 Answer

Box<T> implements the AsRef<T> 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<T> 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 coercion doesn't apply to a cast to a trait object type (the compiler will choose an unsizing coercion instead, which is what happens in your example).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...