Closures as optional function arguments in Rust

1.5k views Asked by At

Is it possible to have closures as optional arguments in functions?

I need something like this (in pseudocode):

fn function(x: int, optional expr |int| -> int) -> int

and usage would be something like this:

// just the mandatory argument
n = function(z);

or optionally:

// passed closure would be called inside the function
n = function(z, |x| x * x);

I just cant grasp the correct syntax if its even possible (would appreciate full example with correct match expressions).

1

There are 1 answers

0
ArtemGr On BEST ANSWER

Optional parameters are in the wish list, but they aren't in the language yet, AFAIK.

What you obviously can do is making two functions

fn function(x: int) -> int {function_with_expr (x, |n|n*n)}
fn function_with_expr(x: int, expr: |int| -> int) -> int

That's the approach used in the standard library.


You can also pass a special trait into the function, like passing ToSocketAddr into bind, and then you might implement that trait for various tuple types. I'm not sure if passing the closure through the tuple will be as simple as passing it directly, though.