Sobes.tech
Middle+

What are generics in Go? How to restrict the set of types (constraints)?

sobes.tech AI

Answer from AI

Generics in Go allow writing generic code that works with different data types while maintaining type safety.

Constraints are interfaces that specify a set of requirements for the types that can be used in generic parameters. They allow restricting permissible types, for example, only numeric types or only types that implement a specific interface.

An example of a constraint using the built-in interface constraints.Ordered (from the package golang.org/x/exp/constraints), which includes all ordered types:

import "golang.org/x/exp/constraints"

func Min[T constraints.Ordered](a, b T) T {
    if a < b {
        return a
    }
    return b
}

Here, the function Min takes two parameters of type T, where T is constrained to types that support the < operator.

You can also create your own constraints:

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

func Sum[T Number](a, b T) T {
    return a + b
}

Here, Number is a custom constraint that allows only the specified numeric types (the ~ symbol means that types with the underlying types from the listed ones are permitted).

Thus, generics and constraints enable writing flexible and safe code by restricting the set of permissible types for function parameters and structures.

What are generics in Go? How to restrict the set of… - sobes.tech