Explain it simply
Explain it simply
A generic function is a function that leaves a placeholder for a type. In Sum[T Number], T says "some number type will go here". Call it with []int and T becomes int; call it with []float64 and T becomes float64. You no longer copy the same code once per type.
T cannot be just anything, though. To use + on it, you must promise the compiler that T is a type that supports addition. That promise is called a constraint, and the Number interface limits T to "int, int64, float64, or types built on them".
Problem → Why → Solution
The problem: one function per type
A shop app needs to total item counts ([]int) and prices ([]float64). Without generics you write SumInts and SumFloats, two functions with identical bodies. Trying a single version over []any is worse: every element needs a type assertion, and a string slipped in by mistake is only discovered at runtime.
func SumInts(xs []int) int {
total := 0
for _, x := range xs { total += x }
return total
}
func SumFloats(xs []float64) float64 { // same body, copied
total := 0.0
for _, x := range xs { total += x }
return total
}
func SumAny(xs []any) float64 { // compiles, but checks types at runtime
total := 0.0
for _, x := range xs { total += x.(float64) } // panics on an int or string
return total
}Why are both approaches poor?
With copied functions, fixing a bug means fixing every copy, and one usually gets forgotten. any moves type checking from compile time to runtime, so x.(float64) panics the moment it meets an int. A type parameter lets you write the logic once while keeping the type checks at compile time.
Core concept: the constraint decides what you may do with T
In generics (part of Go since 1.18), the [T Constraint] after a function name is its type parameter list. When you call Sum([]int{2, 4, 6}), the compiler infers T = int from the argument, so you do not write Sum[int](...). You only spell out the type argument when it cannot be inferred, for example when T appears only in the return type.
A constraint is an interface, but besides methods it can describe a type set. Inside a generic function you may only use operations that every type in the constraint's type set supports. With any you can assign, pass and return values, but not even ==. comparable allows == and !=, which is what map keys and search functions need. The standard library's cmp.Ordered (available since Go 1.21) allows < > <= >= and covers all integer, float and string types.
When you write your own constraint, you join types with |, and the ~ matters. int means exactly int, while ~int means every type whose underlying type is int, including named types like type Kyat int or type Score int. Real code is full of named types, so without ~ you will often see errors such as "Kyat does not satisfy Number".
Types can have type parameters too, as in type Stack[T any] struct { items []T }. You use it with a type argument such as Stack[string], and its methods name the receiver as (s *Stack[T]). An individual method cannot declare extra type parameters of its own. When you need T's zero value, declare var zero T: it is 0 for int, "" for string and nil for pointers.
| Constraint | Operations allowed | Typical use |
|---|---|---|
| any | Assign, pass, return (no ==) | Containers, Map/Filter |
| comparable | == and != | Map keys, Contains, Index |
| cmp.Ordered | < > <= >= and == | Max, Min, sorting |
| ~int | ~float64 | Arithmetic such as + - * / | Sum, Average |
- [T C] leaves a type placeholder
- C defines which types T may be
- Body uses only ops all of them allow
- A call infers T from the arguments
When an operator is rejected, check the constraint before touching the body.
General pattern
type ConstraintName interface { ~TypeA | ~TypeB }
func FuncName[T ConstraintName](param []T) T { ... }
func Other[K comparable, V any](m map[K]V) []K { ... }
type Box[T any] struct { value T }
func (b *Box[T]) Get() T { return b.value }Type parameters go in square brackets [...], each with a constraint. You can have several ([K comparable, V any]), and a generic type's method repeats [T] in its receiver.
Example: Sum with a Number constraint
This example declares its own Number constraint and writes Sum once for three types and every named type built on them. main() calls it with []int, so T becomes int.
package main
import "fmt"
type Number interface { ~int | ~int64 | ~float64 }
func Sum[T Number](values []T) T {
var total T
for _, value := range values { total += value }
return total
}
func main() { fmt.Println(Sum([]int{2, 4, 6})) }Code breakdown
- Constraint
type Number interface { ~int | ~int64 | ~float64 }An interface with a type set and no methods. Thanks to ~, named types such as type Kyat int are included. An interface like this can only be used as a constraint, not as an ordinary variable type.
- Signature
func Sum[T Number](values []T) T {T is constrained by Number, and both the input slice and the result use T. Pass []int and you get an int back, so callers need no type assertion.
- Zero value
var total TStarts from T's zero value: 0 for int, 0.0 for float64. An empty slice simply returns this zero value.
- Loop
for _, value := range values { total += value }Every type in Number supports +, so the compiler accepts +=. Change the constraint to any and this line becomes a compile error.
- Call
func main() { fmt.Println(Sum([]int{2, 4, 6})) }T = int is inferred from the argument, and 2 + 4 + 6 = 12 is printed.
12comparable and cmp.Ordered
Max uses >, so it needs cmp.Ordered, while Index only uses ==, so comparable is enough. Choosing the loosest constraint that works lets the function accept more types; structs, for example, can be comparable but never ordered. You can also pass the type argument explicitly, as in Max[float64](3, 2.5), which makes 3 a float64.
package main
import (
"cmp"
"fmt"
)
// Max works for any ordered type: ints, floats, strings...
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
// Index only needs ==, so the constraint is comparable.
func Index[T comparable](items []T, target T) int {
for i, item := range items {
if item == target {
return i
}
}
return -1
}
func main() {
fmt.Println(Max(3, 7), Max(2.5, 1.5), Max("apple", "banana"))
fmt.Println(Max[float64](3, 2.5)) // explicit type argument
cities := []string{"Yangon", "Mandalay", "Bago"}
fmt.Println(Index(cities, "Bago"), Index(cities, "Taunggyi"))
}The output is "7 2.5 banana", "3" and "2 -1". Strings compare in lexical order, so "banana" is the larger one.
Why ~ lets named types in
The Strict constraint lists exactly int | float64, while Loose uses ~int | ~float64. SumLoose happily accepts a slice of type Kyat int, but passing it to SumStrict fails with "Kyat does not satisfy Strict (possibly missing ~ for int in Strict)"; the compiler even suggests the missing ~.
package main
import "fmt"
type Strict interface{ int | float64 }
type Loose interface{ ~int | ~float64 }
func SumStrict[T Strict](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
func SumLoose[T Loose](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
type Kyat int // underlying type is int
func main() {
prices := []Kyat{1500, 2500, 800}
fmt.Println(SumLoose(prices)) // 4800
fmt.Println(SumStrict([]int{1, 2, 3})) // 6
// SumStrict(prices) does not compile:
// Kyat does not satisfy Strict (possibly missing ~ for int in Strict)
}A generic type: Stack[T]
Stack[T] stores its items in a slice of T. When the stack is empty, Pop() has no T to give back, so it returns the zero value from var zero T along with false, the same comma-ok shape as a map lookup. Stack[string] and Stack[int] are two distinct types at compile time.
package main
import "fmt"
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(v T) {
s.items = append(s.items, v)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last, true
}
func main() {
var pages Stack[string]
pages.Push("home")
pages.Push("cart")
for i := 0; i < 3; i++ {
p, ok := pages.Pop()
fmt.Printf("%q %v\n", p, ok)
}
}The output is "cart" true, "home" true and finally "" false: the last item pushed comes out first.
In real projects
Where this shows up in real projects
Before writing generic code yourself, check the standard library. The slices package (since Go 1.21) has slices.Contains, slices.Index, slices.Sort and slices.Max, and the maps package has functions such as maps.Keys. Open their source and you will see comparable and cmp.Ordered used exactly as in this lesson.
In application code, generics pay off most for data structures (caches, sets, queues, an LRU), type-safe helpers (Map, Filter, GroupBy) and repository layers where CRUD code is identical across entities, as in Repository[T]. When types differ in behavior rather than just in shape, an interface fits better; if your generic function starts switching on T's type, that is a sign you wanted an interface. The usual Go advice is to write the concrete code two or three times before generalizing, not to add type parameters speculatively.
Common mistakes
Common mistakes
1. Using operators under an any constraint
func Biggest[T any](a, b T) T { if a > b ... } fails with "invalid operation: a > b (type parameter T cannot use operator >)", because any promises no operators on T. Switch the constraint to cmp.Ordered, or to comparable if you only need ==.
2. Forgetting ~ in a constraint
With interface{ int | float64 }, passing a slice of type Score int fails with "Score does not satisfy". If you want domain types such as Kyat, Score or UserID accepted, write ~int | ~float64.
3. Reaching for generics where an interface fits
If func Render[T any](v T) immediately does switch any(v).(type) to handle each type separately, generics buy you nothing. When each type behaves differently, use an interface with a Render() method. Generics are for "same logic, different types".
4. Trying to add type parameters to a method
func (s *Stack[T]) Map[U any](f func(T) U) is a compile error: methods cannot have their own type parameters. Write it as a plain generic function instead, such as func MapStack[T, U any](s *Stack[T], f func(T) U).
Mini challenge
Mini challenge: three generic helpers
Write three generic functions with different constraints and try them on both a named Score type and a string slice.
- Filter[T any](items []T, keep func(T) bool) []T keeps only items for which keep returns true
- MaxOf[T cmp.Ordered](items []T) (T, bool) returns the zero value and false for an empty slice
- Count[T comparable](items []T, target T) int
- Call them with both a slice of type Score int and a []string
package main
import (
"cmp"
"fmt"
)
// TODO: Filter — which constraint is enough when you only call keep(item)?
// TODO: MaxOf — handle the empty slice before reading items[0]
func MaxOf[T cmp.Ordered](items []T) (T, bool) {
// TODO
}
// TODO: Count — needs ==
type Score int
func main() {
scores := []Score{72, 95, 48, 95, 60}
// TODO: passed (>= 60), best score, MaxOf on an empty []string,
// how many 95s, how many "go" in []string{"go", "rust", "go"}
fmt.Println(scores)
}Expected: The program prints: passed: [72 95 95 60] best: 95 true empty has max: false count of 95: 2 count of go: 2
Show hint
Filter only calls keep(item), so any is enough. In MaxOf declare var best T first and return best, false when len(items) == 0. In Count(scores, 95), 95 is an untyped constant, so it converts to Score automatically.
Show solution
package main
import (
"cmp"
"fmt"
)
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, item := range items {
if keep(item) {
out = append(out, item)
}
}
return out
}
func MaxOf[T cmp.Ordered](items []T) (T, bool) {
var best T
if len(items) == 0 {
return best, false
}
best = items[0]
for _, item := range items[1:] {
if item > best {
best = item
}
}
return best, true
}
func Count[T comparable](items []T, target T) int {
n := 0
for _, item := range items {
if item == target {
n++
}
}
return n
}
type Score int
func main() {
scores := []Score{72, 95, 48, 95, 60}
passed := Filter(scores, func(s Score) bool { return s >= 60 })
fmt.Println("passed:", passed)
best, ok := MaxOf(scores)
fmt.Println("best:", best, ok)
_, ok = MaxOf([]string{})
fmt.Println("empty has max:", ok)
fmt.Println("count of 95:", Count(scores, 95))
fmt.Println("count of go:", Count([]string{"go", "rust", "go"}, "go"))
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- [T Constraint] is a type placeholder, and calls usually infer T from the arguments.
- The constraint decides what the body may do with T: any (no operators), comparable (==), cmp.Ordered (< >).
- ~int accepts every named type whose underlying type is int; plain int means exactly int.
- Generic types such as Stack[T] are allowed, but methods cannot add type parameters of their own.
- Same logic with different types calls for generics; different behavior calls for an interface.