A user in the Discord was confused by a compiler error this code generated:
fn f(cb: &dyn Fn() -> dyn Send) {
(cb)();
}
error[E0618]: expected function, found `&dyn Fn() -> (dyn Send + 'static)`
--> src/lib.rs:2:5
|
1 | fn f(cb: &dyn Fn() -> dyn Send) {
| -- `&dyn Fn() -> (dyn Send + 'static)` defined here
2 | (cb)();
| ^^^^--
| |
| call expression requires function
I'd say this error should explain that the trait object isn't callable because the return type is unsized, and preferably before we even try to call it. I would normally file an issue on the bug tracker, but the minimal example came with a few surprises.
It turns out this compiles -
trait Assoc {}
trait Trait {
type Type: Assoc;
}
type Impossible = dyn Trait<Type = ()>;
Instead, rustc only complains once we try to use it: the dyn Trait<Type = ()>
doesn't implement Trait
. Why do trait objects behave like this?