3 Structs, interfaces, and generics
This chapter covers
- Using custom structures (or structs) to represent data and methods
- Comparing Go’s structs and interfaces against 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 look dig into some of the core building blocks of the language. We’ll start with a little more depth on the non-primitive data structure in Go: the struct. Structs are the cornerstone of how we represent bespoke data and relationships between data. Go provides a system for building, extending, and manipulating these data structs. In this chapter we’ll explore how structs, interfaces, and methods work together to empower you to design intuitive data structures, their methods, and using them for data isolation/control and state management.
3.1 Using structs to represent data
In the first two chapters we built some basic command line applications and a web server, utilizing the custom data structures. In Go, structs are powerful language tools which represent rich data structures beyond primitives and can be used to define the behaviors and data flow of your applications. Used thoughtfully, they keep your code readable and free of cruft and code duplication, as well as accommodating encoding data with tags.