liveBook · Manning

Type inference

As explained in Refactoring to Rust

Type inference is the compile-time deduction of expression or variable types from program context without requiring explicit annotations.

Type inference lets the Rust compiler determine local variable types from program context, so most variables need no explicit annotations. Function inputs and outputs still require annotations, and inferred types remain statically checked. section 1.4.3

Infer a map’s types from its contents

Rust can infer the map and vector types from the inserted values: `let mut map = HashMap::new(); map.insert(1, vec![4, 10]);`. The equivalent explicit form is `let mut map: HashMap<i32, Vec<i32>> = HashMap::new();`; both express the same structure, but the annotations are usually optional. section 1.4.3

Infer a variable from its initializer

A variable initialized with `let` receives its type from the value on the right-hand side. For example, an artwork value is inferred as the declared `Artwork` struct, while `.to_string()` produces the required `String` field value. section 2.1

Listing 1.3 Initializing a map of numbers to lists of numbers in Java 1.6
HashMap<Integer, ArrayList<Integer>> map
  = new HashMap<Integer, ArrayList<Integer>>();

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(10);

map.put(1, list);

Compare the verbose Java 1.6 map declaration with the shorter Rust initialization, then inspect the optional explicit Rust annotation. section 1.4.3

How Refactoring to Rust covers it

How deep it goes
Explains inference through initializers and map insertion, while deferring detailed annotation cases to later treatment.
Examples
Contrasts Java and Rust map declarations and demonstrates inferred artwork variables initialized with structs and strings.
What it assumes
Assumes familiarity with variables and values, while introducing Rust’s static typing without requiring prior annotation-heavy syntax.
What you can do after
Apply it via the Rust compiler by omitting routine local annotations while checking that surrounding values constrain the intended types.
How it connects
Connects type inference with static typing, type checking, type annotations, and function signatures.

Also explained in

Compare how 16 books explain type inference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.