6 Generics
This chapter covers
- How to use Generics in Go
- Creating Generics with Interfaces and Structs
- Defining type parameters for Generics
- Creating functions with Generics
- Using Generics with the standard library
Computer science is built on various layers of abstraction. Electrical pulses lead to binary code which leads to assembly code and so on. In the last chapter, we looked at abstractions in the form of types but in this section, we will be exploring another layer of abstractions on top of that known as generics
Generics have long been one of the most requested features in the Go programming language. Before their introduction, Go developers relied heavily on interfaces and code generation to achieve type flexibility. While these approaches provided some level of abstraction, they often resulted in verbose, repetitive code and increased the risk of runtime errors due to the lack of compile-time type safety.
To address the need for flexible data structures, Go provided built-in types like map
and slice
. These types are flexible in the kinds of values they can store, and their design allows for operations such as adding, accessing, or removing elements. For example, the range
keyword can be used to iterate over both maps and slices, showcasing a form of generic-like behavior. However, it’s important to note that while map
and slice
offer some of the benefits associated with generics, they are not themselves generic constructs—they are specific types built into the language.