What enables a closure type to be used where a function pointer type is expected in Rust?

Viewed 550
1 Answers

Closures can be coerced to function pointers if they do not capture any local variables.

Closures that don't capture any variables are effectively the same as normal functions, making this sound. This behaviour was defined in RFC 1558, which says:

A closure that does not move, borrow, or otherwise access (capture) local variables should be coercable to a function pointer (fn).

So |n| n can be coerced since it doesn't capture any local variables, but |n| n + a cannot be coerced since it captures a variable, a, from the outer environment.

Related