
3 Structs, interfaces, and generics
This chapter covers
- Using structs to represent data and methods
- Comparing Go’s structs and interfaces with object-oriented and functional programming patterns
- Creating interfaces to extend functionality of custom types
- Making code more flexible and reusable by implementing generic types
As we move toward more complex features and approaches in Go, including concurrency, let’s first dig into some of the core building blocks of the language. We’ll start by going into a little more depth on the nonprimitive data structure in Go. Custom structures, or structs, are the cornerstone of how we represent bespoke data and relationships between data. Go provides a system for building, extending, and manipulating data structs. In this chapter, we’ll explore how structs, interfaces, and methods work together to empower you to design intuitive data structures and their methods and use them for data isolation/control and state management.
3.1 Using structs to represent data
In chapters 1 and 2, we built some basic command-line applications and a web server, using the custom data structures. In Go, structs are powerful language tools that represent rich data structures beyond primitives; you can use them to define the behaviors and data flow of your applications. Used thoughtfully, they keep your code readable and free of cruft and code duplication; they also accommodate encoding data with tags.