Constraints
Constraints are interfaces that define the capabilities a type must have to be used with a generic function.
Method-Based Constraints
If your function needs to call a method on the generic type, you must specify a constraint that includes that method.
type stringer interface {
String() string
}
func concat[T stringer](vals []T) string {
result := ""
for _, v := range vals {
result += v.String() // Safe to call because T is constrained by stringer
}
return result
}
The any Constraint
The any constraint is the most permissive; it allows any type because it requires no methods. It is identical to interface{}.
Why use constraints?
Without constraints, the Go compiler wouldn’t know what operations are safe to perform on the generic type. Constraints provide the “contract” that the caller must fulfill.