GoGo
AdvancedLesson 14 of 15

Generics – Go

Type parameters, constraints and generic types (since Go 1.18).

With generics you write functions and types once for many types. Type parameters go in square brackets; a constraint determines which operations are allowed. any allows everything, comparable allows ==, and cmp.Ordered (since Go 1.21) allows < and >.

package main

import (
	"cmp"
	"fmt"
	"strconv"
)

func Map[T, U any](s []T, f func(T) U) []U {
	res := make([]U, 0, len(s))
	for _, v := range s {
		res = append(res, f(v))
	}
	return res
}

func Max[T cmp.Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

func main() {
	fmt.Println(Map([]int{1, 2, 3}, func(x int) string { return strconv.Itoa(x * x) })) // [1 4 9]
	fmt.Println(Max(3, 7), Max("a", "b"))                                             // 7 b
}

Custom constraints are interfaces with a type set. The tilde ~int also includes custom types whose underlying type is int. Generic types get their parameters on the type name:

package main

import "fmt"

type Zahl interface {
	~int | ~int64 | ~float64
}

func Summe[T Zahl](werte []T) T {
	var s T
	for _, w := range werte {
		s += w
	}
	return s
}

type Stapel[T any] struct{ items []T }

func (s *Stapel[T]) Push(v T) { s.items = append(s.items, v) }

func (s *Stapel[T]) Pop() (T, bool) {
	var zero T
	if len(s.items) == 0 {
		return zero, false
	}
	v := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return v, true
}

func main() {
	fmt.Println(Summe([]float64{1.5, 2.5})) // 4
	fmt.Println(Summe([]int{1, 2, 3}))      // 6

	var st Stapel[string]
	st.Push("a")
	st.Push("b")
	v, ok := st.Pop()
	fmt.Println(v, ok) // b true
}

The standard library itself uses generics: slices, maps and cmp offer ready-made generic helpers, so you rarely have to write your own:

package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Person struct {
	Name  string
	Alter int
}

func main() {
	leute := []Person{{"Ada", 36}, {"Bob", 25}, {"Cem", 41}}
	slices.SortFunc(leute, func(a, b Person) int {
		return cmp.Compare(a.Alter, b.Alter)
	})
	fmt.Println(leute) // [{Bob 25} {Ada 36} {Cem 41}]

	i, gefunden := slices.BinarySearch([]int{2, 5, 8}, 5)
	fmt.Println(i, gefunden) // 1 true
}
TipUse generics sparingly: if an interface is enough (e.g. io.Reader), that is simpler. They make sense for containers, helper functions such as Map/Filter and algorithms over different numeric types.