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?
Pl
I think unfortunately the answer for that particular problem is "you can't use a stored closure with
filter_entry
"
The approach from Shepmaster's answer can be applied to achieve this goal. Like in that answer, we can define a generic constrain
function requiring a type with the kind of lifetime bounds that will be required to satisfy filter
. We apply the function to the closure and then store it to. Note that calling constrain(cb)
when invoking filter
(which was my first attempt) doesn't work because the compiler cannot infer the type of the closure variable when it is passed to constrain
any more than it could when it was being passed to filter
.
The invocation of constrain
has no effect at run-time, it just guides the compiler to infer the lifetime bounds for the variable that we need for filter
. This allows storing the closure and calling filter
without modifying its signature:
fn constrain(fun: F) -> F
where
F: for<'a> Fn(&'a S) -> bool,
{
fun
}
fn main() {
let cb = constrain(|_s| true);
filter(cb);
}
Playground.