Since Go 1.18, type parameters enable generic functions and types: func Map[T, U any](s []T, f func(T) U) []U. Use when algorithms repeat for many types—avoid premature abstraction.
Constraints
func Sum[T ~int | ~float64](nums []T) T {
var total T
for _, n := range nums { total += n }
return total
}
Constraints live in interfaces—comparable, any, or custom union constraints with |.
Compared to Java/C#
Go generics are reified but simpler than Java wildcards or C# variance—still prefer interfaces when behavior differs, not just types.
Important interview questions and answers
- Q: When use generics?
A: Shared algorithms on slices/maps/channels across types—containers and utilities, not every struct. - Q: any vs interface{}?
A:anyis alias for empty interface—prefer in generic constraints for clarity.
Self-check
- What Go version added generics?
- What keyword declares type parameters?
Pitfall: Do not genericize everything—prefer plain functions until the same algorithm repeats for many unrelated types.
Interview prep
- When use generics?
Shared algorithms across types—containers and utilities, not every struct field.
- Go version for generics?
Go 1.18+ with type parameters and constraints.