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