chapter five

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, types define the properties and rules for representing data. We have already encountered a few built-in types, called primitive types, such as integers, floats, Booleans, and strings, which 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.

But real-world problems often require us to model more complex concepts than primitive types allow. By combining these 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 Type embedding

5.2.2 Complex types

5.3 Pointer types

5.4 Methods and behavior

5.5 Interfaces

5.6 Checking types

5.6.1 Type composition and wrapping

5.6.2 Example: Putting it all together

Summary