liveBook · Manning

Type safety

As explained in Go in Action, Second Edition

Type safety is the property that prevents operations from applying values in ways inconsistent with their types.

A value that reaches the wrong code path can produce an error long after it was assigned. Go moves many such failures to the build: every value has a type, the compiler tracks it, and incompatible assignments are rejected before the program runs. Fast compilation makes that check part of the everyday development loop. section 1.2.2 section 1.0

Listing 1.2 Type mismatch caught at compile time
var number int
var str string

number = 1
str = "one"
number = str
// Error: cannot use str (variable of type string) as int in assignment

The final assignment tries to put a string into an int variable. The compiler reports the mismatch; the program never reaches that line at runtime. section 1.2.2

Type safety also shapes domain design. Named types can represent measurements and units; structs group recipe data; embedded types distinguish measurement concepts; and interfaces express shared behaviors such as scaling or conversion. These choices make the model clearer while giving the compiler more structure to check. section 5.0 section 5.6.2

Generics extend compile-time checking to reusable functions and collections without requiring a separate implementation for each type. Use them when the same logic serves multiple types or a result must preserve its contents’ exact type. If one concrete type suffices, or an interface already captures the needed behavior, simpler code is preferable. section 6.0 section 6.5.4

How Go in Action, Second Edition covers it

How deep it goes
Explains assignment rejection and applies type checking to composed domain types and generics without claiming to prevent every runtime error.
Examples
Uses a rejected string-to-int assignment and a recipe model with measurements, ingredients, scaling, and conversion.
What it assumes
Assumes familiarity with primitive types while explaining type checking through assignments and contrasting it with dynamic-language errors.
What you can do after
Diagnose/debug with it by using Go compiler errors to catch incompatible assignments before running or deploying code.
How it connects
Connects type safety to named types, structs, interfaces, composition, and generics.

Also explained in

Compare how 8 books explain type safety →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.