By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Generics were added in Go 1.18 to express algorithms and collections without any and type assertions. The syntax is familiar: square brackets declare type parameters, and a constraint describes the operations the parameter must support. comparable allows == and map keys; any allows nothing but assignment; a union such as ~int | ~int64 | ~float64 allows arithmetic on the listed underlying types.
The ~ matters. ~int means 'any type whose underlying type is int', so a named type such as type Status int satisfies the constraint too. Without ~, only the exact predeclared type qualifies. Use generics for code that is genuinely reusable across types — map, filter, reduce, min/max, caches — and keep business logic concrete. An over-generic function is harder to read and usually earns nothing.
Callers rarely write type arguments explicitly. If the parameters can be inferred from the arguments, Map(events, fn) is enough. Reach for explicit instantiation only when inference is ambiguous, or when you are calling with an empty collection and there is nothing to infer from.
package main
import (
"fmt"
"slices"
)
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 Map[T, U any](values []T, transform func(T) U) []U {
result := make([]U, 0, len(values))
for _, value := range values {
result = append(result, transform(value))
}
return result
}
func CountBy[T any, K comparable](values []T, key func(T) K) map[K]int {
counts := make(map[K]int, len(values))
for _, value := range values {
counts[key(value)]++
}
return counts
}
type event struct {
Service string
Status int
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.5}))
levels := Map([]event{{Service: "api", Status: 200}, {Service: "worker", Status: 503}}, func(e event) string {
if e.Status >= 500 {
return "error"
}
return "ok"
})
fmt.Println(levels)
counts := CountBy([]event{
{Service: "api", Status: 200},
{Service: "api", Status: 404},
{Service: "worker", Status: 500},
}, func(e event) string { return e.Service })
services := make([]string, 0, len(counts))
for service := range counts {
services = append(services, service)
}
slices.Sort(services)
for _, service := range services {
fmt.Println(service, counts[service])
}
}Generics do not replace interfaces. If the behavior differs per type, an interface is the right abstraction; if the code is identical except for the element type, generics pay off. Avoid generic APIs whose only instantiation is one type, and avoid constraints that quietly force reflection. The standard slices and maps packages now cover most collection work, so your own generic helpers should be few and obviously useful.
| Constraint | Allows | Typical use |
|---|---|---|
any | Assignment, passing, storing | A container that never inspects values |
comparable | ==, !=, map keys | Deduplication, grouping |
~int | ~int64 | Arithmetic on listed underlying types | Counters, sums, IDs |
fmt.Stringer | Calling String() | Formatting generic values |
| Ordered (custom) | Comparisons | Min/max before the built-ins cover it |
Key takeaways
Type parameters plus constraints express algorithms that work across types.
comparable enables equality and map keys; any enables only storage and passing.
~T in a constraint admits named types whose underlying type is T.
Go infers type arguments at call sites; explicit instantiation is rarely needed.
Use generics for containers and algorithms, interfaces for varying behavior, and concrete code for business rules.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.