impl Trait
首先,让我说这个问题与语法的使用无关。我将闭包转换为命名结构并得到相同的结果。
所以,让我们看一下您想要运行的代码:
let f = apply(second, i);
let _ = tuples.iter().filter(f);
编译器对此有什么看法?
error[E0277]: the trait bound `for<'r> impl std::ops::FnMut<(&(_, _),)>: std::ops::FnMut<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` is not satisfied
--> <anon>:11:27
|
11 | let _ = tuples.iter().filter(f);
| ^^^^^^ trait `for<'r> impl std::ops::FnMut<(&(_, _),)>: std::ops::FnMut<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` not satisfied
error[E0277]: the trait bound `for<'r> impl std::ops::FnMut<(&(_, _),)>: std::ops::FnOnce<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` is not satisfied
--> <anon>:11:27
|
11 | let _ = tuples.iter().filter(f);
| ^^^^^^ trait `for<'r> impl std::ops::FnMut<(&(_, _),)>: std::ops::FnOnce<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` not satisfied
好的,所以我们有类型 X,它需要实现特征 Y,但它没有。但让我们仔细看看:
for<'r> impl
std::ops::FnMut<(&(_, _),)>:
std::ops::FnMut<(&'r &(_, _),)>
啊哈!filter
期望一个函数接受对元组引用的引用,而我们传入的函数接受对元组的引用。filter
传递对引用的引用,因为tuples.iter()
迭代引用,并filter
传递对这些的引用。
好吧,让我们更改 的定义second
以接受对引用的引用:
fn second<'a, A, B: ?Sized>(&&(_, ref second): &&'a (A, B)) -> &'a B {
second
}
编译器仍然不高兴:
error[E0277]: the trait bound `for<'r> impl std::ops::FnMut<(&&(_, _),)>: std::ops::FnMut<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` is not satisfied
--> <anon>:11:27
|
11 | let _ = tuples.iter().filter(f);
| ^^^^^^ trait `for<'r> impl std::ops::FnMut<(&&(_, _),)>: std::ops::FnMut<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>` not satisfied
error[E0271]: type mismatch resolving `for<'r> <impl std::ops::FnMut<(&&(_, _),)> as std::ops::FnOnce<(&'r &(&str, &std::ops::Fn(i32) -> bool),)>>::Output == bool`
--> <anon>:11:27
|
11 | let _ = tuples.iter().filter(f);
| ^^^^^^ expected bound lifetime parameter , found concrete lifetime
|
= note: concrete lifetime that was found is lifetime '_#24r
expected bound lifetime parameter , found concrete lifetime
... 这意味着什么?
f
的类型是实现的某种类型FnMut(&'c &'b (&'a str, &Fn(i32) -> bool)) -> bool
。在对和的调用apply
中。请注意,这里是一种固定类型;表示一个固定的生命周期,称为具体生命周期。B == &'c &'b (&'a str, &Fn(i32) -> bool)
C == bool
B
'c
让我们看一下filter
的签名:
fn filter<P>(self, predicate: P) -> Filter<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,
在这里,P
必须实施FnMut(&Self::Item) -> bool
。实际上,这种语法是for<'r> FnMut(&'r Self::Item) -> bool
. 这里。'r
是一个绑定的生命周期参数。
所以,问题是我们实现的函数FnMut(&'c &'b (&'a str, &Fn(i32) -> bool)) -> bool
没有实现。我们需要一个实现. 目前,这样做的唯一方法是这样写:for<'r> FnMut(&'r Self::Item) -> bool
for<'c> FnMut(&'c &'b (&'a str, &Fn(i32) -> bool)) -> bool
apply
fn apply<A, B, C, F, G>(mut f: F, a: A) -> impl FnMut(&B) -> C
where F: FnMut(&B) -> G,
G: FnMut(A) -> C,
A: Clone
{
move |b| f(b)(a.clone())
}
或更明确的版本:
fn apply<A, B, C, F, G>(mut f: F, a: A) -> impl for<'r> FnMut(&'r B) -> C
where F: for<'r> FnMut(&'r B) -> G,
G: FnMut(A) -> C,
A: Clone
{
move |b| f(b)(a.clone())
}
如果 Rust 最终支持更高种类的类型,可能会有更优雅的方法来解决这个问题。