Generics
Part of the Go course
You write a function that finds the largest number in a slice of int. Then you need one for float64, so you copy it and change two words. Then one for string. Now three near-identical functions exist, and when you fix a bug in one, you get to remember the other two.
For most of its life Go had no clean answer to this. You either duplicated the function, or you used interface{}, which accepted anything and gave up all type checking, so the compiler could no longer tell you that you had passed a slice of the wrong thing. Duplication or blindness, pick one.
Want to learn Go Generics in a real environment?
Click below, get a fresh Linux box with Go ready to go, and work through Generics hands-on with an AI tutor that knows your code.
Start this lessonGenericsWhat you'll learn
- Type parameters with [T any]
- Constraints
- Comparable
- Tilde approximation ~int
- Generic Map and Filter
- When generics help, when they do not
Read this lesson in your language
All lessons in this course
20 lessons- 1Hello, Go25 min
- 2Variables and Types25 min
- 3Control Flow: if and for30 min
- 4Functions30 min
- 5Slices and Maps35 min
- 6Structs and Pointers35 min
- 7Methods and Interfaces35 min
- 8Error Handling35 min
- 9Modules and Project Structure35 min
- 10Tiny CLI Capstone40 min
- 11A Tour of the Standard Library40 min
- 12Testing and Benchmarks40 min
- 13Goroutines and Channels40 min
- 14Concurrency Patterns45 min
- 15Generics35 min
- 16HTTP Servers45 min
- 17Databases with database/sql45 min
- 18Performance and Profiling40 min
- 19Design Patterns in Go40 min
- 20Deployment and Production45 min
