Type parameters

Function can be written to work with multiple types using type parameters.

func Index[T comparable](s []T, x T) int

This declaration means that s is a slice of any type T that fulfills the built-in constraint comparable. x is also a value of the same type.

Constraints

Go uses constraint-based approach for generics.

Constraints are used to create a union of allowed types:

type MyConstraint interface {
  int | int8 | int16 | int32 | int64
}

There’s a built-in constraint type comparable. At the moment I didn’t find any info on other types. I’ll add them later here.

Built-in constraint types:

  • comparable - allows == and != operations
  • any

Generic types

Go also supports generic types:

type List[T any] struct {
	next *List[T]
	val  T
}