Go core
Browse topics

Generics and type constraints

Version
1.27
Since
1.18
Review
Draft

Summary#

Type parameters let one function or type work with several types. A constraint limits the allowed type arguments and decides which operations the code may use. ~int admits every type whose underlying type is int.

Syntax#

go
type Number interface{ ~int | ~float64 }

func Sum[T Number](values []T) T
type Set[T comparable] map[T]struct{}

Example#

go
package main

import "fmt"

type number interface{ ~int | ~float64 }

type cents int

func sum[T number](values []T) T {
	var total T
	for _, value := range values {
		total += value
	}
	return total
}

type set[T comparable] map[T]struct{}

func (s set[T]) has(value T) bool {
	_, ok := s[value]
	return ok
}

func main() {
	total := sum([]cents{150, 275})
	fmt.Printf("%T %d\n", total, total)
	fmt.Println(sum([]float64{1.5, 2.25}))

	colors := set[string]{"red": {}}
	fmt.Println(colors.has("red"), colors.has("blue"))
}

Expected output#

Text
main.cents 425
3.75
true false

Common mistakes#

A constraint written as int | float64 rejects defined types such as cents. Add ~ when those should be accepted. A value of type parameter type cannot be used in a type switch directly. Convert it with any(value) first. A set instantiated with any can still panic if a key's dynamic type is a slice or another non-comparable type.

Version applicability#

The example requires Go 1.18, including the method that uses its receiver type's parameters. Since Go 1.20, interface types such as any can satisfy comparable. Go 1.27 lets a method declare its own type parameters. Interface methods still cannot declare them, and generic methods cannot implement interface methods. On Go 1.26 and earlier, write a generic function instead.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0