Type constraints in Go are defined using the type keyword with a ~ prefix or a list of interfaces to restrict generic type parameters. They ensure that only types satisfying specific conditions can be used with a generic function or type.
// Define a constraint allowing any type that supports addition
type Addable interface {
int | int8 | int16 | int32 | int64 | float32 | float64 | ~string
}
// Use the constraint in a generic function
func Sum[T Addable](items ...T) T {
var total T
for _, item := range items {
total += item
}
return total
}