Rust By Example: Return Functions as Output

Опубликовано: 03 Май 2026
на канале: Stephen Blum
242
4

You may ask why a function should return a closure. But, if closures can be passed as inputs, why not have them as outputs? The great thing is, with Rust, this is possible.

You might be wondering exactly how this works? Well, you create a function that returns a function. It might sound unusual, and most times you don't need it, but the "factory pattern" illustrates this idea well.

Consider a generator producing closures that take data from you to create a state that changes over time every time the function is called. To do this, in Rust, you have to implement a trait and choose from three options: 'Fn', 'FnMut', and 'FnOnce'. After implementing your function, it gets confirmed when the compiler implicitly understands that we're returning a closure that's referencing other values here.

Now, imagine writing a function that returns a function. It might seem complex at first glance, but with some hands-on application, it becomes manageable. And, yes, you might question its necessity, but there are instances where it can be useful.

For instance, you could use closures to track how many times a function was called. It involves creating a factory function that returns a mutable function. Inside it, there's a variable, 'times'.

This variable counts the number of times that the function was called. A closure is created and returned by moving all variables in the scope to the closure. Then, every time this function is called, the 'times' variable is incremented and its value is printed out.

But, would you use this mechanism? Or would you use a more traditional pattern like having a mutable element in a struct? It's up to you.

Your choice should fulfill one central aim: provide an interface that gives the best user experience while minimizing the complexity for the user. They should be able to utilize your library with ease, without worrying about the behind-the-scenes mechanics. This approach might change as AI code generation improves, or it may not.

But for now, it's the best way to ensure user-friendly coding.