Closed
Description
The following code:
trait MyTrait {}
struct Foo {
val: Box<dyn MyTrait>
}
fn make_it(val: &Box<dyn MyTrait>) {
Foo {
val
};
}
produces the following error:
error[E0308]: mismatched types
--> src/lib.rs:9:9
|
9 | val
| ^^^
| |
| expected struct `Box`, found reference
| help: store this in the heap by calling `Box::new`: `Box::new(val)`
|
= note: expected struct `Box<(dyn MyTrait + 'static)>`
found reference `&Box<(dyn MyTrait + 'static)>`
= note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html
error: aborting due to previous error
val
is a &Box<dyn MyTrait>
, so writing Box::new(val)
would produce a Box<&Box<dyn MyTrait>>
. This is very unlikely to be what the user wants - and in this case, it won't even work, since there are no impls for MyTrait
.
Meta
Tested on rustc 1.52.0-nightly 2021-02-22