I'm investigating object safety with traits in rust and based on the following piece of code, I have a couple of questions.
trait Foo {}
trait Bar : Foo {}
struct Baz;
impl Foo for Baz {}
impl Bar for Baz {}
fn do_foo(_: &Foo) {
println!("Doing foo stuff.");
}
fn do_bar(_: &Bar) {
println!("Doing bar tuff.");
}
fn main() {
let x = Baz;
let y: &Foo = &x;
do_foo(y);
let y: &Bar = &x;
do_bar(y);
// do_foo(y); -- Does not compile with mismatched types error, Expected: &Foo, found &Bar
}
- Since
Bar
inherits fromFoo
, why is it not possible to coerce&Bar
to&Foo
? - Is there a workaround to this issue that does not require declaring
do_foo
as generic? It may be the case thatdo_foo
itself may need to exist on a object-safe trait.