Why is it possible to infer the types of arguments and return type for a closure expression while not for a function in rust?
Basic Types in Rust Instructor: [00:00] The Rust compiler comes with a feature called type inference.
Type inference means that if you don't tell the compiler the type, but it can decide by itself, it will decide. The compiler always needs to know the type of the variables, but you don't always need to tell it. Actually, usually you don't need to tell it. For example, for let my_number = 8 , my_number will be an i32 .
Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they're defined.
Rust closures are harder for three main reasons: The first is that it is both statically and strongly typed, so we'll need to explicitly annotate these function types. Second, Lua functions are dynamically allocated ('boxed'.)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With