Object inheritance and trait inheritance
I am researching the safety of objects with traits in rust and based on the following code snippet I have a few 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 it
Bar
inherits fromFoo
, why is it impossible to coerce&Bar
to&Foo
? - Is there a workaround that doesn't need to be declared
do_foo
as generic? It is possible that it itselfdo_foo
can exist on an object-safe basis.
+3
source to share
No one has answered this question yet
See similar questions:
or similar: