Why won\'t this compile?
trait T {}
fn f(f2: V) -> impl Fn() -> Result
It's a limitation and I don't know if it will compile one day. The reason is that Rust doesn't know to convert between the two Result
types, (dyn T + 'static)
and U
are totally different things. If this acceptable you can do f2().map(|x| Box::new(x) as _)
.
The cast will allow the compiler to transform U
into (dyn T + 'static)
before put it in the result, we don't need to explicit the cast type the compiler inference will do it for us (on most case).
A trait object can be obtained from a pointer to a concrete type that implements the trait by casting it (e.g. &x as &Foo)
See dynamic dispatch section of the book (didn't find any information in the new book).