Appendix D. Object-oriented programming
This appendix discusses object-oriented programming in Go.
NOTE
If you're unfamiliar with variables, pointers, arrays, maps, and slices, review Appendices A to C, as the upcoming topics may be challenging to understand.
Go's philosophy emphasizes clarity and simplicity, avoiding unnecessary complexity.
Object-oriented programming in Go is different from most other languages: Go shifts the focus from rigid and complicated type hierarchies to behavior (i.e., methods). This approach often results in simpler and more maintainable programs, whether on small or large scales.
First, Go has no concept of classes. Go allows us to add methods to any of our concrete types, including integer, map, slice, and function types. This eliminates the need to declare classes to define behavior, making our code simpler, more expressive, and more flexible.
Second, Go avoids inheritance and uses interfaces for polymorphism.
Concrete types can implicitly satisfy interfaces by implementing all their methods without specifying the interface names. This decouples concrete types from interfaces, letting us focus on behavior rather than type hierarchies. We can start with concrete types and defer declaring interfaces until they naturally emerge, keeping code adaptable as it grows.
In this section, we'll begin with structs, then cover methods. Finally, unlike other languages, we'll learn how to discover interfaces naturally rather than define them upfront.