liveBook · Manning

Type checking

As explained in Refactoring to Rust

Type checking is the process of verifying that values and operations conform to the rules of a type system.

Type checking verifies that values match the types required by a program. During JSON deserialization, a Rust struct makes those expectations explicit: `name` must be a `String`, while `value` must be an `i32`. section 6.3

Type mismatches appear at different stages:

  • The compiler requests a type annotation when `serde_json::from_str` cannot infer the result type. section 6.3
  • The compiler rejects deserialization until the struct implements `Deserialize` and supports the requested formatting. section 6.3
  • Serde reports an input mismatch at runtime when JSON supplies a string where the struct requires an integer. section 6.3

A mismatched JSON field

Changing `Data.name` from `String` to `i32` leaves the JSON input unchanged but causes deserialization to fail: `invalid type: string "Sharpe Oliver", expected i32`, with line and column information. section 6.3

Listing 6.6 JSON parsing code with a run-time type error
#[derive(Debug, serde::Deserialize)]
struct Data {
  name: i32,  #1
  value: i32,
}

fn main() {
  let input = "{ \"name\": \"Sharpe Oliver\", \"value\": 134087 }";  #2

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

  println!("{:?}", parsed);
}

Inspect the complete Rust example that introduces the mismatched field and demonstrates type checking during JSON parsing. section 6.3

How Refactoring to Rust covers it

How deep it goes
Explains inference, trait requirements, and runtime mismatch errors, but defers broader Serde configuration options.
Examples
Demonstrates typed `Data` structs, compiler diagnostics, and a JSON string whose `name` field incorrectly contains text.
What it assumes
Assumes basic Rust structs and JSON parsing while demonstrating required annotations and `Deserialize` implementation.
What you can do after
Diagnose JSON type mismatches using compiler messages and Serde's line-and-column runtime errors.
How it connects
Connects Rust types with JSON parsing, deserialization, Serde, traits, and error handling.

Also explained in

Compare how 5 books explain type checking →

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.