liveBook · Manning

Type hints

As explained in Refactoring to Rust

A type annotation is source-code syntax that explicitly declares the type associated with a value, variable, parameter, or return result.

A type hint, or type annotation, explicitly associates a type with a value, variable, parameter, or return result. Rust requires function inputs and outputs to be annotated, while usually inferring local variable types statically. section 1.4.3

Use annotations when inference needs direction or when an interface benefits from explicit types:

  • Annotate a generic result when the compiler cannot infer the expected type. section 6.3
  • Leave ordinary local types inferred when surrounding operations make them unambiguous. section 1.4.3
  • Use explicit input and output types to make function contracts clear and prevent incompatible values. section 1.4.3

Guiding JSON deserialization

A JSON parser has a generic return type, so Rust needs a target type: `let parsed: Data = serde_json::from_str(input).unwrap();`. The annotation identifies the desired struct; deriving `Deserialize` then enables parsing, while deriving `Debug` enables formatted output. section 6.3

let parsed: Data = serde_json::from_str(input).unwrap();

Shows the smallest annotation that resolves the compiler's ambiguous JSON result. section 6.3

How Refactoring to Rust covers it

How deep it goes
Provides worked Rust and JSON examples, but defers broader annotation cases to later treatment.
Examples
Uses JSON parsing, typed structs, map initialization, and contrasting Java and Rust declarations.
What it assumes
Assumes basic Rust syntax and introduces static typing without requiring explicit annotations for most local variables.
What you can do after
Diagnose compiler inference errors and apply explicit annotations to Rust functions, collections, and deserialization results.
How it connects
Connects type annotations with static typing, type inference, generic functions, traits, and JSON deserialization.

Also explained in

Compare how 17 books explain type hints →

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.