15

Why is it possible to infer the types of arguments and return type for a closure expression while not for a function in rust?

2

1 Answer 1

27

This is simply a design decision: Rust employs local type inference, but not global type inference. It is theoretically possible to do global type inference, but for ease of debugging Rust has consciously eschewed it, for it can lead to extremely difficult-to-debug compilation issues (e.g. a minor change in this part causes a compilation error deep in the internals).

Functions are global—their type signatures must thus be explicit.

Closures, being inside a function, are local—their types can be inferred. (Of course, if you are storing a closure in a struct, its type will need to be explicitly specified in the struct’s type definition.)

1
  • 2
    Some functions are private like local closures. So inferring return type for private function has the same value as local closures.
    – EvanL00
    Apr 2, 2021 at 2:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.