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 one function or type work with different kinds of values while Go still checks their types before the program runs. A type parameter is a name for a type supplied when the function is used. Write type parameters in square brackets.

The comparable rule requires the type to support ==. Go figures out T from each call, so this function can search slices of numbers or strings.

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 steps should work with several types. For a function that only needs one type, a regular function is often easier to read. Add type parameters only when they make repeated code simpler.

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