为什么这个代码无法编译?
错误信息如下:
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) }
}
错误信息如下:
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
这个版本可以使用:
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),
}
}
}
我的观点是,(dyn T + 'static)
和 U
是相同的;我是对的吗?
我正在使用的版本是 rustc 1.39.0-nightly (f0b58fcf0 2019-09-11)
。
as X
的一部分。看起来这是一个非常有用的功能。可惜它没有更好的文档说明。 - Michael Anderson