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 allow you to define functions, types, and interfaces with type parameters, enabling the same code to operate on different data types while maintaining strict type safety enforced at compile time. Introduced in Go 1.18, generics give you a way to write reusable algorithms and data structures without duplicating code for each specific type or sacrificing compile-time safety.
In this chapter, we will explore the core concepts and practical applications of generics in Go by examining a set of generic collection types and utility functions (lists, sets, and maps), building up from how type parameters work to increasingly powerful patterns.
6.1 Typed Parameters in Generics
To see why generics matter, consider the recipe application we built in the previous chapter. Suppose you want a function that filters a slice down to only the elements that match some condition. Without generics, you would need a separate function for every type: