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 could 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, type 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.

Final note: I wanted to put this in the "suggestions" category, but there is none! Anyway, here is the playground link: Rust Playground

There's a complete different forum for that - it is called IRLO. Please post it there.

1 Like