0

This code:

trait A {}

trait B: A {}

struct S;

impl A for S {}

impl B for S {}

fn main() {
    let s = S;
    let trait_obj_b: &B = &s;
    let trait_obj_a: &A = trait_obj_b;
} 

fails with the error:

error[E0308]: mismatched types
  --> src/main.rs:14:27
   |
14 |     let trait_obj_a: &A = trait_obj_b;
   |                           ^^^^^^^^^^^ expected trait `A`, found trait `B`
   |
   = note: expected type `&A`
              found type `&B`

Why? Since B requires A, shouldn't all trait objects &B automatically implement &A? Is there a way to convert &B to &A without changing trait definitions or implementations?

Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    I believe your question is already answered by [Why doesn't Rust support trait object upcasting?](https://stackoverflow.com/q/28632968/155423). If you disagree, please [edit] your question to explain the difference. Otherwise, we can mark this as already answered. – Shepmaster Apr 24 '18 at 14:38
  • @Shepmaster Thanks for the link, I somehow missed it! Although the accepted answer is 3 years old, but if there is really no way to upcast trait objects without implementation modification, please close this one as duplicate. – Sergey Mitskevich Apr 24 '18 at 14:46

0 Answers0