Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in Type inference for closures and functions in rust

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

like image 201
Viswanadh Kumar Reddy Vuggumud Avatar asked Jul 27 '14 02:07

Viswanadh Kumar Reddy Vuggumud


People also ask

Does rust use type inference?

Basic Types in Rust Instructor: [00:00] The Rust compiler comes with a feature called type inference.

How does rust type inference work?

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 .

What are closures in Rust?

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.

Why Rust closures are somewhat hard?

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


1 Answers

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

like image 102
Chris Morgan Avatar answered Oct 26 '22 02:10

Chris Morgan