You create type constraints in Go by defining a type parameter with a ~ prefix for underlying types or a specific interface, then using that constraint in a generic function or type definition. This allows the compiler to enforce that only types matching the constraint (like all integers or all types with a String method) can be used.
// Define a constraint for all integer types
// The ~ prefix matches the underlying type
// This allows int, int32, int64, uint, etc.
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
// Use the constraint in a generic function
func Sum[T Integer](values ...T) T {
var total T
for _, v := range values {
total += v
}
return total
}
// Usage
result := Sum(1, 2, 3) // Works with int
result64 := Sum[int64](100, 200) // Works with int64