Programming

Generics in Go, Explained

The majority of programming languages have the concept of generic functions — code that can easily and efficiently accept one of a range of types without needing any specialization for each one – as long as those types all implement certain types of behaviors. Generics are a massive time-saver.…

Generics in Go, Explained

Generic functions take a range of types without a separate implementation per type — write sum once, run it on every numeric type. Most languages had them for years before Go did.

What Go had instead

Pre-1.18, the answer was interface{}: treat everything the same, check types at runtime. It worked, and it moved every mistake to production. The other workaround was duplication:

func sumInt8(s []int8) int8 {
    var total int8
    for _, i := range s { total += i }
    return total
}
func sumInt64(s []int64) int64 {
    var total int64
    for _, i := range s { total += i }
    return total
}
// and float64, and...

Type parameters on constraints

Go's generics parameterize a function over types bounded by an interface constraint:

func sum[T ~int8 | ~int64 | ~float64](s []T) T {
    var total T
    for _, i := range s { total += i }
    return total
}

sum([]int64{1, 2, 3})   // T inferred as int64

The union ~int8 | ~int64 | ~float64 says what T may be; the ~ means "or any type with that underlying type" — so your custom type Score int64 still matches. The compiler generates type-specific code at build time; old code keeps compiling untouched.

Generic types too

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 {
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v
}

When to bother

Collections and algorithms over multiple types: sums, maps, filters, containers. The signal is a duplicated body differing only in type. If you're not duplicating, generics are indirection for nothing — reach for them when the duplication shows up.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.