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

十年热恋 提交于 2020-01-30 08:08:47

问题


Why won't this compile?

trait T {}

fn f<U: 'static + T, V, E>(f2: V) -> impl Fn() -> Result<Box<dyn T>, E>
where
    V: Fn() -> Result<U, E>,
{
    move || -> Result<Box<dyn T>, E> { f2().map(Box::new) }
}

The error message is:

error[E0308]: mismatched types
 --> src/lib.rs:7:40
  |
7 |     move || -> Result<Box<dyn T>, E> { f2().map(Box::new) }
  |                                        ^^^^^^^^^^^^^^^^^^ expected trait T, found type parameter
  |
  = note: expected type `std::result::Result<std::boxed::Box<(dyn T + 'static)>, _>`
             found type `std::result::Result<std::boxed::Box<U>, _>`
  = help: type parameters must be constrained to match other types
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

This version is ok:

trait T {}

fn f<U: 'static + T, V, E>(f2: V) -> impl Fn() -> Result<Box<dyn T>, E>
where
    V: Fn() -> Result<U, E>,
{
    move || -> Result<Box<dyn T>, E> {
        match f2() {
            Ok(result) => Ok(Box::new(result)),
            Err(e) => Err(e),
        }
    }
}

In my opinion, (dyn T + 'static) and U are the same; am I right?

I'm using rustc 1.39.0-nightly (f0b58fcf0 2019-09-11).


回答1:


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



来源:https://stackoverflow.com/questions/59476676/failed-to-infer-type-when-using-resultmap-and-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!