Differences in Type inference for closures and fun

2019-02-21 22:49发布

问题:

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

回答1:

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.)