Failed to infer type when using Result::map and Box

后端 未结 1 490
离开以前
离开以前 2020-12-04 03:01

Why won\'t this compile?

trait T {}

fn f(f2: V) -> impl Fn() -> Result

        
1条回答
  •  伪装坚强ぢ
    2020-12-04 03:43

    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).

    0 讨论(0)
提交回复
热议问题