5 Working With Types

 

This chapter covers

  • How Go’s type system lets you model real-world domains using named types, structs, and composition.
  • Defining and using custom types, struct embedding, and collections to organize and extend your data.
  • Attaching methods and interfaces to types to add behavior and enforce contracts.
  • Working with pointers, type assertions, and type switches to manage memory and check concrete types at runtime.

In computer science, a type defines the properties and rules for representing data. We have already experienced a few built-in types—called primitive types—such as integers, floats, booleans, and strings to represent basic values like numbers, truth values, and text. A programming language’s type system is the set of rules and features it provides for defining and working with types. However, real-world problems often require us to model more complex concepts. By combining primitive types, we can create composite or complex types that better represent real-world entities and their relationships. This allows us to model domains more accurately, enforce rules in our code, and build safer, more expressive programs.

5.1 Modeling a Domain with Types

5.1.1 Named Types

5.1.2 Structs

5.2 Extending Types

5.2.1 Complex Types

5.3 Pointer Types

5.3.1 Methods and Behavior

5.4 Interfaces

5.5 Checking Types

5.5.1 Type Composition and Wrapping

5.5.2 Example: Putting It All Together

5.6 Summary