【发布时间】:2019-11-08 21:27:20
【问题描述】:
我构建了一个无法开始工作的闭包示例,也找不到任何不应该工作的原因。为什么最后一次闭包编译失败?
struct S {}
fn filter<P>(predicate: P)
where
P: Fn(&S) -> bool,
{
predicate(&S {});
}
fn main() {
// this works
filter(|_s| true);
// this also works
fn cb1(_s: &S) -> bool {
true
}
filter(cb1);
// but this doesn't work
let cb2 = |_s| true;
filter(cb2);
}
输出:
error[E0631]: type mismatch in closure arguments
--> /tmp/closure.rs:19:5
|
18 | let cb2 = |_s| true;
| --------- found signature of `fn(_) -> _`
19 | filter(cb2);
| ^^^^^^ expected signature of `for<'r> fn(&'r S) -> _`
|
note: required by `filter`
--> /tmp/closure.rs:3:1
|
3 | fn filter<P>(predicate: P) where P: Fn(&S) -> bool,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0271]: type mismatch resolving `for<'r> <[closure@/tmp/closure.rs:18:15: 18:24] as std::ops::FnOnce<(&'r S,)>>::Output == bool`
--> /tmp/closure.rs:19:5
|
19 | filter(cb2);
| ^^^^^^ expected bound lifetime parameter, found concrete lifetime
|
note: required by `filter`
--> /tmp/closure.rs:3:1
|
3 | fn filter<P>(predicate: P) where P: Fn(&S) -> bool,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
【问题讨论】:
-
看来Type mismatches resolving a closure that takes arguments by reference 的答案可能会回答您的问题。如果没有,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。