It seems that Rust checks trait object type differently when passing as reference? The following builds OK:
fn print_foo(value: Box<dyn MyTrait + Send>) {
println!("{}", value.say());
}
fn main() {
let f = Foo{};
print_foo(Box::new(f));
}
but the following does not build:
fn print_foo(value: &Box<dyn MyTrait + Send>) {
println!("{}", value.say());
}
fn main() {
let f = Foo{};
print_foo(&Box::new(f));
}
the error message is:
error[E0308]: mismatched types
--> src/main.rs:20:15
|
20 | print_foo(&Box::new(f));
| ^^^^^^^^^^^^ expected trait object `dyn MyTrait`, found struct `Foo`
|
= note: expected reference `&Box<(dyn MyTrait + Send + 'static)>`
found reference `&Box<Foo>`
Why did the build succeed when passing the value directly? Here is the full program in Playground.