Go - Generics
Beginner 10/10
Teacher 10/10
Architect 10/10
Try it: Write a generic
Min[T constraints.Ordered]
for two values.Generic Functions
func Map[T any, R any](in []T, f func(T) R) []R {
out := make([]R, len(in))
for i, v := range in { out[i] = f(v) }
return out
}
Constraints
type Number interface{ ~int | ~int64 | ~float64 }
func Sum[T Number](xs ...T) T {
var s T
for _, x := range xs { s += x }
return s
}
Guidelines
- Use generics when it clarifies code or removes duplication.
- Prefer concrete types when behavior is specific.
Common errors
- Overusing generics—prefer concrete types unless duplication or clarity improves.
Practice
- Write
Map[T any, R any]
and test it with[]int
and[]string
.
Quick quiz
- What’s a type constraint?
Show answer
A set of permitted types for a type parameter (e.g.,constraints.Ordered
).