How to receive a closure and pass an inner closure to it?

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]).


  1. on stable Rust, but might be possible with TAIT ↩︎

1 Like

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....

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.