3

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
}
  1. Since Bar inherits from Foo, why is it not possible to coerce &Bar to &Foo?
  2. Is there a workaround to this issue that does not require declaring do_foo as generic? It may be the case that do_foo itself may need to exist on a object-safe trait.
Joshua Rodgers
  • 5,317
  • 2
  • 31
  • 29

0 Answers0