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.

Type errors arise when values are used in ways incompatible with their types. Go tracks the type of every value and rejects mismatches at build time, catching many errors before deployment rather than waiting for a particular code path to run. section 1.2.2 section 5.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

Assigning a string to an int fails at compilation, so the incompatible assignment cannot reach a running program. section 1.2.2

Type safety also supports domain modeling. Named types and structs represent measurements and recipes, while composition combines simpler types into richer ones. Interfaces and methods add shared behaviors such as scaling recipes and converting measurements. section 5.0 section 5.6.2

Generics let functions and types work across multiple data types while retaining compile-time type safety. They are useful when shared logic or a type relationship must be preserved, but a plain interface or concrete type can be clearer when genericity adds no real benefit. section 6.0 section 6.5.4

How Go in Action, Second Edition covers it

How deep it goes
Explains compiler rejection of an incompatible assignment and applies type-system features in a recipe application.
Examples
Uses a string-to-int assignment and a recipe application with measurements, scaling, and a grocery list.
What it assumes
Assumes familiarity with primitive types before combining them into domain-specific types.
What you can do after
Apply type safety in Go by modeling domains with named types and composition and choosing generics when type relationships warrant them.
How it connects
Connects type safety to composition, interfaces, generics, and compile-time type checking.

Also explained in

Compare how 11 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.