If you know Go, then you need to know all about interfaces, generics, and iterators: they’re key parts of modern Go. Learn all about type parameters and constraints in Go and how to use them, with this easy-to-read but comprehensive guide to programming with generics and iterators in Go.
If you’re new to Go and generics, and wondering what all the fuss is about, this book is for you! If you have some experience with Go already, but want to learn about the new generics features, this book is also for you. And if you’ve been waiting impatiently for Go to just get generics and iterators already so you can use them, don’t worry: this book is for you too!
You don’t need an advanced degree in computer science or tons of programming experience. Know Go: Generics explains what you need to know in plain, ordinary language, with simple examples that will show you what’s new, how the language changes will affect you, and exactly how to use generics in your own programs and packages.
As you’d expect if you enjoyed my previous books, For the Love of Go and The Power of Go: Tools, this is fun and easy reading, but it’s also packed with powerful ideas, concepts, and techniques that you can use in real-world applications.
What you’ll learn
By reading through this book and completing the exercises, you'll learn
What we mean by generic programming in general, and specifically how that applies to Go
What type parameters are, and how they’re different from interfaces
How to declare and write generic functions, and when that's necessary (and when it's not)
How generics are implemented in Go, and how that affects the way we write programs
How to define and use constraints on type parameters, and what constraints are provided in the standard library and the Go language itself
How to write type element and type approximation constraints, as well as understanding the changes to interfaces
What operations are allowed on generic types,
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
Tip the Site
Support this siteYour recognition and a small knowledge-service contribution help keep this technical work open source.Scan the WeChat Pay or Alipay code below. Logged-in and guest visitors can both tip.
WeChat Pay
Alipay
Open WeChat or Alipay and scan. No login required.
AI guide
# Know Go: Generics — Reading Guide
## 【One-Line Pitch】
A practical, friendly guide to Go's generics and iterators—type parameters, constraints, and the new iterator pattern—written for working Go developers who want to use these features confidently in real code without a CS degree.
## 【Book Arc】
- **Opening (~0%–9%)**: Sets the stage by explaining why generics matter for modern Go, what generic programming means, and what you'll learn—type parameters, constraints, implementation details, and iterators. Includes a table of contents mapping the full journey from basics to advanced topics.
- **Early (~9%–25%)**: Builds the conceptual foundation by contrasting specific programming (fixed types) with polymorphism via interfaces. Shows why interfaces alone fail for operations like `+` or identity functions that must preserve type relationships, motivating the need for type parameters.
- **Early–Middle (~25%–38%)**: Introduces generic functions with `[T any]` syntax, composite types (slices, channels, variadic functions), and generic types like `Group[E]`. Then pivots to constraints—why `any` is too loose, and how method-set constraints (like `fmt.Stringer`) give Go enough information to allow operations.
- **Middle (~38%–47%)**: Dives into type-set constraints: writing interfaces that list allowed types directly (like `interface { int }`), using `~` for type approximations, handling empty type sets, and the crucial pattern of interface literals that reference type parameters (e.g., `interface{ Equal(T) bool }`).
- **Late (~47%–end)**: Covers operations enabled by constraints (arithmetic on numeric types), discusses implementation trade-offs, addresses common questions (compile speed, why not angle brackets), and introduces iterators—`iter.Seq`, `iter.Seq2`, error handling, cleanup, composition, and when iterators beat channels.
## 【Key Takeaways】
- **Interfaces give polymorphism but not type preservation** (Early): An `io.Writer` parameter accepts many concrete types, but you can't write a function that returns the *same* concrete type it received. This limitation motivates generics.
- **Type parameters express relationships `any` cannot** (Early): `func Identity[T any](v T) T` guarantees the return type matches the input type—something impossible with `any` or interfaces. Go instantiates a concrete version per type at compile time.
- **Constraints are the key to useful generic code** (Middle): Constraining `T` to `any` means you can't add, compare, or call methods. Method-set constraints like `fmt.Stringer` unlock real operations while keeping type safety.
- **Type-set constraints allow non-method restrictions** (Middle): `interface { int }` lets you restrict to specific types (not just method holders), enabling arithmetic on generic values. The `~` symbol extends this to derived types like `type MyInt int`.
- **Interface literals can reference type parameters** (Middle): `func Contains[T interface{ Equal(T) bool }](s []T, v T) bool` is the *only* way to write constraints where the method signature involves `T` itself—named interfaces can't express this.
- **Empty type sets are a real failure mode** (Middle): `interface { int; string }` has no satisfiable types; Go reports "empty type set." Understanding this error helps debug over-constrained generic code.
- **Iterators are a new composition tool** (Late): `iter.Seq` and `iter.Seq2` provide a function-based iteration pattern that composes well, handles errors cleanly, and often beats channels for sequential data processing.
- **Generics have deliberate limitations** (Late): No parameterized methods, no generic packages, no macros, no union types. Understanding what Go *doesn't* do helps you choose idiomatic alternatives.
## 【Reading Tips】
- **Skim the early interface review** (~10%–16%) if you're comfortable with Go interfaces; it's groundwork for the generics motivation but moves quickly.
- **Deep-read the constraints chapters** (~34%–47%): This is the conceptual core. Work through the `Double`, `Contains`, and `StringifyTo` examples by hand—they illustrate the three constraint styles (method set, type set, approximation).
- **Do the exercises** (like `Group`, `intish`, `product`): They're confidence-builders that cement syntax and constraint patterns. The test-driven examples show how generics integrate with normal Go testing.
- **Pay attention to error messages** (Middle): The book unpacks cryptic errors like "operator + not defined on T" and "empty type set"—learning to read these will save you hours.
- **The iterator chapter** (~Late) is practical and standalone; if you're primarily interested in iterators, you can read it after the constraints chapters without losing context.
## 【Coverage Limits】
This guide synthesizes the book's core progression through generics and iterators. The excerpts don't cover the full implementation details of generics in the Go compiler, nor the complete standard library iterator changes—those sections are referenced but not fully excerpted.
##
Excerpt 1
raints, as well as understanding the changes to interfaces What operations are allowed on generic types, 4. Operations 51 Arithmetic . . . . . . . . . . . ....
it has a Writemethod, it’ll be acceptable to our function. The fancy computer science term for this is polymorphism (“many forms”). But it just means we can...
l. This is a very handy feature of Go, and we use it a lot. Generic functions as values So what if that function were generic? For example, the Identity[T] f...
ed some named interface type to do the same thing. Why not? Let’s see what happens if we try: type Equaler interface { Equal( ) bool // we can't say 'T' here...
one of those functions, doesn’t it? Specifically, the Dupes function needs to look at every slice element in turn, and if that same value has oc‐ curred befo...
double every integer in a slice, we could write some func‐ tion double that doubles its input, and “map” that function over the slice. The result would be a...
n(s.Contains(1)) // Output: // true Let’s get to work! 98 } While we’re at it, we’ll make the same change to Add, so that we can add any number of new member...
ing channels in Go a little too freely, and a scheme is now proposed to bill users by activity. Accordingly, you’ll need to define a generic Channel 115 } wg...
Support this siteYour recognition and a small knowledge-service contribution help keep this technical work open source.
Scan the WeChat Pay or Alipay code below. Logged-in and guest visitors can both tip.
WeChat PayAlipay
Open WeChat or Alipay and scan. No login required.
Add Tag
Enter tag name (max 50 characters)
Share E-Book
Know Go - Generics (John Arundel)(Z-Library)
Scan QR code with your phone to access
Copy the link or scan the QR code to access this e-book on your phone
Share to WeChat Moments
Know Go - Generics (John Arundel)(Z-Library)
Scan the QR code with WeChat to open this book
Tap the ··· menu in the top-right corner
Choose Share to Moments
You are already in WeChat. Tap ··· in the top-right corner and choose Share to Moments.
Share E-Book via Email
Please enter email address
Donation Statistics
¥.00
Total Donations
0
Donation Count
Know Go - Generics (John Arundel)(Z-Library)
Find Your Favorite Books
Only registered users can comment after logging in. Comments need to be reviewed by administrators before being displayed
这本书围绕现代 Go 语言中的接口、泛型和迭代器展开,作者 John Arundel 面向已经了解 Go、但希望掌握类型参数与约束的读者,系统讲解泛型编程与迭代器的使用方式。全书从读者可能存有的疑问切入——如果你刚接触 Go 和泛型,不明白这些特性为何重要,这本书正是为此而写。它并不停留在语法层面,而是把泛型放回接口与多态的背景中理解:一个类型只要拥有某个方法(例如 Write 方法),就能被函数接受,这种“多种类型”可作参数的能力就是多态,而泛型让这种能力表达得更自然、更安全。
读者可以抓住几条主要线索。其一是类型参数与约束:书中讲解类型参数的作用范围,以及如何用约束限定可接受的类型,让泛型代码既灵活又不失类型安全。其二是接口与多态的关系:从基本接口出发,逐步引入另一种接口形式,说明接口如何支撑“多态”这一看似高深的术语背后的朴素含义。其三是复合类型与错误信息:书中讨论由其他类型构建而成的复合类型,例如切片类型,并教读者读懂编译器报错,从而定位和修复问题。其四是泛型函数的实际运用:以查找重复元素、Map、Filter、Reduce 等例子展示泛型如何...
Digital LibraryAI Assistant
Hi — I can help you pick a book. Tell me a topic, language, or level, e.g. “a light English read”. If that's too broad, I'll ask one follow-up.
Loading comments...
Reply to Comment
Edit Comment