I've constructed a closure example that I can't get to work, nor can I find any reason why it shouldn't work. Why does it fail to compile on the last closure?
Playground
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);
}
Output:
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,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…