Chapter 5. Go’s type system


In this chapter

  • Declaring new user-defined types
  • Adding behavior to types with methods
  • Knowing when to use pointers and values
  • Implementing polymorphism with interfaces
  • Extending and changing types through composition
  • Exporting and unexporting identifiers

Go is a statically typed programming language. What that means is the compiler always wants to know what the type is for every value in the program. When the compiler knows the type information ahead of time, it can help to make sure that the program is working with values in a safe way. This helps to reduce potential memory corruption and bugs, and provides the compiler the opportunity to produce more performant code.

A value’s type provides the compiler with two pieces of information: first, how much memory to allocate—the size of the value—and second, what that memory represents. In the case of many of the built-in types, size and representation are part of the type’s name. A value of type int64 requires 8 bytes of memory (64 bits) and represents an integer value. A float32 requires 4 bytes of memory (32 bits) and represents an IEEE-754 binary floating-point number. A bool requires 1 byte of memory (8 bits) and represents a Boolean value of true or false.

5.1. User-defined types

5.2. Methods

5.3. The nature of types

5.4. Interfaces

5.5. Type embedding

5.6. Exporting and unexporting identifiers

5.7. Summary