Go by Example

Generics

Go 1.18 added generics - type parameters let you write functions and types that work across multiple types without losing type safety.

Generics let functions and types work with multiple types while keeping compile-time type checking. A type parameter is written in square brackets.

The comparable constraint allows equality operators. Go infers T from each call, so this function can search slices of different comparable types.

package main
 
import "fmt"
 
func Contains[T comparable](values []T, want T) bool {
    for _, value := range values {
        if value == want {
            return true
        }
    }
    return false
}
 
func main() {
    fmt.Println(Contains([]int{1, 2, 3}, 2))
    fmt.Println(Contains([]string{"go", "rust"}, "go"))
}

In production

Use generics when the same algorithm or data structure should work for several types. With interface element types, a comparison using == can still panic if a dynamic value is not comparable. Choose concrete types when generalization adds little or makes the domain rules harder to understand.

Enjoyed this? Get more software craft delivered to your inbox.