Can you specify argument names in a lambda declaration?

The sitauation

Let's say that have a function that accepts a callback, like this:

fn accept_function(callback: fn(name: String, age: u32)) { ... }

We can clearly see what the arguments that the callback will be getting are (name and age), which is really helpful.

Now, what if we want to pass in an lambda instead of a function?

fn accept_lambda(callback: &dyn Fn(name: String, age: u32)) { .. } // syntax error!

We cannot specify the argument names! Instead, we have to do:

fn accept_lambda(callback: &dyn Fn(String, u32)) { ... }

Which erases the argument names and makes the signature less clear about what is going on.

Why does this matter?

As someone who is coming from TypeScript, I often rely on type signatures to understand what is going on, and Fn(String, u32) really doesn't tell me anything.

You could say that this is a bad design, and you should pass in a Person struct in this case or something, and while that has some merit, this argument has 2 problems:

  • The fn signature accepts parameter names, so by this logic, that should be types only as well, and it clearly isn't.
  • Sometimes creating a struct is an overkill, like in the fold method.

In the fold example in particular, I can never remember which argument is the current value and which is the accumulator, and if both have the same type, the type signature will tell me nothing really about it.

You can say "just put it in the annotation", and while that is certainly a good idea, I would still prefer to have the information about which argument is for what in the argument name, and not in the description of the method that accepts the lambda function that has the parameter.

Proposed solution

Make specifying argument types in lambda declarations possible, just like in function declarations. As this would be optional, I see no possible downside.

One additional benefit would be that code editors might "autofill" the lambda parameter list for you when using the method from the argument names, making it more convenient to write lambdas.

And by the way, here is the playground link: Rust Playground Thanks for consideration.

3 Likes

I've always wanted that, but was too lazy to fill a RFC :smile:

One possible counterargument is that it will make the Fn traits too special, however they're already pretty special with the parentheses and HRTB lifetimes.

RFC issue for this - Naming arguments in Fn traits · Issue #2812 · rust-lang/rfcs · GitHub.

I assigned that issue to myself back in 2019 with an aim to eventually implement it, but never got to it due to low priority.

7 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.