As in JavaScript, we can create a closure in a function, and then pass it to another closure in the argument list, like this:
function foo(f) {
f(() => {});
}
foo((g) => {
g();
});
How to implement that with generic types in Rust?
As in JavaScript, we can create a closure in a function, and then pass it to another closure in the argument list, like this:
function foo(f) {
f(() => {});
}
foo((g) => {
g();
});
How to implement that with generic types in Rust?
Unfortunately, there is no “perfect” way to do this, but this is the closest reasonable thing you can write:
fn foo<F>(f: F)
where
F: Fn(&dyn Fn()),
{
f(&|| {});
}
fn main() {
foo(|g| {
g();
});
}
The &
is to allow using dyn
, and the dyn
is to avoid having to give a name for the specific type of the closure that foo
passes to f
(which is currently impossible[1]).
Thanks! I now try to use an older way to solve it: use a struct
to capture the envirenment explicitly and implement an assosiated function to do what the original inner closure does....