🎓 A1Learner
🔍

Rust Type Inference

Type inference is Rust guessing a type from how a value is used. Rust also looks at later lines that use the variable.

A later line pins the type

value is born with no type written down. The next line saves it into a u8, so value was a u8 all along:

let value = 42;
let small: u8 = value;
println!("small = {}", small);

One clear clue is enough

The same trick works for decimals. One annotation on a later line reaches back and settles the first line:

let amount = 2.5;
let precise: f32 = amount;
println!("amount = {}", amount);

No clue? The compiler stops

An empty array gives no clue at all: nothing sits inside it to learn from. This code fails with error E0282, and Rust asks you to write the type:

let values = [];
println!("{:?}", values);

Settle it yourself

An annotation ends the guessing at once — now even an empty array has a known type:

let values: [u8; 0] = [];
println!("{:?}", values);

Example

fn main() {
    let value = 42;
    let small: u8 = value;
    println!("small = {}", small);
    let amount = 2.5;
    let precise: f32 = amount;
    println!("amount = {}", precise);
}

Key points

  • Rust looks at the line where a variable is created.

In this example, value is born with no type written down. The next line saves it into small, a u8 — so value was a u8 all along. The same trick works for amount: the f32 annotation on precise reaches back and settles amount as an f32. Delete a clue line and nothing is left to learn from. With a truly empty start, like an empty array, the compiler stops with E0282 and asks for an annotation.

Note

Inference happens while compiling, not while running.

By the time your program runs, every type is fixed and known.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What happens if you write let values = []; and then print values?