问题
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