1

I have a struct Foo that implements traits A and B, where B is a sub-trait of A. I now pass a &Foo to function alpha taking a &B, which works as expected. However, when in function alpha I try to pass the pointer to function beta which takes a &A, the compiler complains that it expected trait A, but got trait B. See the following code:

trait A {}
trait B : A {}

struct Foo {}
impl A for Foo {}
impl B for Foo {}

fn alpha(x: &B) {
    beta(x);
}

fn beta(x: &A) {}

I would expect this to work, since the functions in trait B are a superset of the functions in A. So given the vtable of B, I should be able to construct the vtable of A by just picking the right function pointers. Explicit casting (x as &A) does not help either. Why does this not work?

Fabian Schuiki
  • 1,268
  • 7
  • 18

0 Answers0