Chapter 2. Types

In the previous chapter, we used the data type string to store Hello, World. Data types categorize a set of related values, describe the operations that can be done on them, and define the way they are stored. Because types can be a difficult concept to grasp, we will look at them from a couple different perspectives before we see how they are implemented in Go.

Philosophers sometimes make a distinction between types and tokens. For example, suppose you have a dog named Max. Max is the token (a particular instance or member) and dog is the type (the general concept). Dog or dogness describes a set of properties that all dogs have in common. Although oversimplistic, we might reason like this: all dogs have four legs, Max is a dog, therefore Max has four legs. Types in programming languages work in a similar way: all strings have a length, x is a string, therefore x has a length.

In mathematics, we often talk about sets. For example, ℝ (the set of all real numbers) or ℕ (the set of all natural numbers). Each member of these sets shares properties with all the other members of the set. For instance, all natural numbers are associative: “for all natural numbers a, b, and c, a + (b + c) = (a + b) + c and a × (b × c) = (a × b) × c.” In this way, sets are similar to types in programming languages, because all the values of a particular type share certain properties.

Go is a statically typed programming language. This means that variables always have a specific type and ...

Get Introducing Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.