Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust's type inference work across multiple statements?

Rust performs type inference in fairly advanced situations. Could someone please explain (or point to) the rules that describe what can and cannot be inferred?

The first one is simple: The type of a binding is the type of the bound expression:

let n = 10u32;

// Same as:
//   vvvvv
let n: u32 = 10u32;

This next one is more surprising to me: The generic parameter on the right is deduced from the binding type on the left:

let n: u32 = "10".parse().unwrap();

// same as:            vvvvvvv
let n: u32 = "10".parse::<u32>().unwrap();

This also works for "member functions" of generic types:

let b = Box::new(10u32);

// same as:
//        vvvvv      vvvvvvv
let b: Box<u32> = Box::<u32>::new(10u32);

But the strangest of all is type inference across statements:

let v = Vec::new();   // no type!
v.push(10u32);        // apparently v is Vec<u32>?!
// v.push(10i32);     // type error

What are the rules for type inference and type deduction?

like image 578
Kerrek SB Avatar asked May 31 '16 10:05

Kerrek SB


People also ask

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.

Does rust use type inference?

Rust performs type inference in fairly advanced situations.

Why do we type inferences?

The ability to infer types automatically makes many programming tasks easier, leaving the programmer free to omit type annotations while still permitting type checking.

Is Hindley Milner in Rust?

Rust uses Hindley-Milner type inference. OCaml uses Hindley-Milner. Swift apparently uses a variant of the system with more features.


1 Answers

Rust uses Hindley-Milner type system. It is a set of rules about establishing types of expressions based on their usage.

Formal description and explanation for it can be found there:

"What part of Hindley-Milner do you not understand?"

like image 75
Hauleth Avatar answered Sep 18 '22 13:09

Hauleth