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.

6.1 Typed Parameters in Generics

6.1.1 Using Interface Constraints

6.1.2 Defining Custom Constraints

6.1.3 Leveraging Underlying Types with Tilde (~)

6.1.4 Summary of Type Constraints

6.2 Implementing Generic Functions

6.3 Implementing Generic Interfaces

6.4 Multiple Type Parameters

6.5 Limitations and Considerations

6.5.1 Performance Considerations

6.5.2 Limitations of Go Generics

6.5.3 Common Gotchas

6.5.4 Backwards Compatibility

6.6 Standard Library support

6.6.1 The constraints Package

6.6.2 The slices and maps

6.6.3 The cmp Package

6.7 Just getting started

6.8 Summary