我想为特定类型的闭包实现特征。这是一个最小的示例(playground):
trait Foo {
fn foo(&self, x: &u32);
}
impl<F> Foo for F
where F: Fn(&u32)
{
fn foo(&self, x: &u32) {
self(x)
}
}
fn main() {
let _: &FnOnce(&u32) = &|x| {}; // works
let _: &Foo = &|x| {}; // doesn't work
}
导致此错误:
error: type mismatch resolving `for<'r> <[closure@<anon>:16:29: 16:35] as std::ops::FnOnce<(&'r u32,)>>::Output == ()`:
expected bound lifetime parameter ,
found concrete lifetime [--explain E0271]
--> <anon>:16:28
|>
16 |> let _: &Foo = &|x| {};
|> ^^^^^^^
note: required because of the requirements on the impl of `Foo` for `[closure@<anon>:16:29: 16:35]`
note: required for the cast to the object type `Foo`
error: type mismatch: the type `[closure@<anon>:16:29: 16:35]` implements the trait `std::ops::Fn<(_,)>`, but the trait `for<'r> std::ops::Fn<(&'r u32,)>` is required (expected concrete lifetime, found bound lifetime parameter ) [--explain E0281]
--> <anon>:16:28
|>
16 |> let _: &Foo = &|x| {};
|> ^^^^^^^
note: required because of the requirements on the impl of `Foo` for `[closure@<anon>:16:29: 16:35]`
note: required for the cast to the object type `Foo`
我已经尝试过将HRTB显式添加到
where
子句中,如下所示:where F: for<'a> Fn(&'a u32)
但这没有帮助。我还改为在
impl
块上声明了生存期,如下所示:impl<'a, F> Foo for F
where F: Fn(&'a u32) { ... }
但这会导致
impl
块内出现生命周期错误。我认为这些错误是正确的,并且不能在impl
块上声明生命周期参数。我该如何解决这个例子?
最佳答案
查看错误的这一部分:
我认为基本上没有足够的代码来允许正确推断类型。添加显式类型注释可以编译示例:
let _: &Foo = &|x: &u32| {};
关于rust - 为闭包实现特征会导致绑定(bind)/具体生命周期不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39356633/