2

I have the following code:

trait Foo {}

trait Bar: Foo {}

struct Baz {
    baz: Box<dyn Foo>,
}

impl Baz {
    pub fn new_bar(baz: Box<dyn Bar>) -> Baz {
        Baz { baz }
    }
}

fn main() {}

This fails to compile because:

error[E0308]: mismatched types
  --> foo.rs:14:13
   |
14 |             baz
   |             ^^^ expected trait `Foo`, found trait `Bar`
   |
   = note: expected struct `Box<(dyn Foo + 'static)>`
              found struct `Box<(dyn Bar + 'static)>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

However, Bar is a subtrait(?) of Foo. Therefore this should typecheck -- why is rustc complaining, and how can I fix this?

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
Alex Coleman
  • 607
  • 1
  • 4
  • 11
  • 1
    Does this answer your question? [Why doesn't Rust support trait object upcasting?](https://stackoverflow.com/questions/28632968/why-doesnt-rust-support-trait-object-upcasting) – Elias Holzmann Sep 10 '21 at 16:11
  • 1
    There is a very nice explanation here: https://articles.bchlr.de/traits-dynamic-dispatch-upcasting – Svetlin Zarev Sep 10 '21 at 16:14
  • There are at least 2 ways to answer this question depending on what angle you come at it from. First, traits are not types, and [subtrait does not imply subtype](https://stackoverflow.com/q/55200843/3650362). But that by itself does not explain why [you can't coerce `dyn Bar` to `dyn Foo` anyway](https://stackoverflow.com/q/57817405/3650362), even though `dyn Foo` does implement `Bar` (question uses `str`, but the same reasoning applies). Both the links above show how you can work around this by adding a method to the trait. – trent Sep 10 '21 at 16:32

0 Answers0