Type constraints
August 4, 2023
Are you as curious about Fuzzing in Go as I am? On Monday’s live stream, I’ll be live coding my way through John Arundel’s 4-part series on Go Fuzzing. I hope you’ll [join me!](https://youtube.com/live/VKV-sFFeSQw
Type constraints
A type constraint is an interface that defines the set of permissible type arguments for the respective type parameter and controls the operations supported by values of that type parameter.
TypeConstraint = TypeElem .
If the constraint is an interface literal of the form
interface{E}
whereE
is an embedded type element (not a method), in a type parameter list the enclosinginterface{ … }
may be omitted for convenience:[T []P] // = [T interface{[]P}] [T ~int] // = [T interface{~int}] [T int|string] // = [T interface{int|string}] type Constraint ~int // illegal: ~int is not in a type parameter list
We’ve already seen type constraints, so they shouldn’t be a surprise. But here we get a nice juicy tidbit: The interface{ … }
syntax is optional in many cases. Actually, what’s likely more surprising is not that it can be omitted, since that’s how we usually see it, but that it can be included.
By way of example, the following type constraints are equivalent:
func print1[T int | string](arg T) {
fmt.Print(arg)
}
func print2[T interface{ int | string }](arg T) {
fmt.Print(arg)
}
But this only works for type elements, not methods.
func print3[T String() string](arg T) {} // Invalid!
func print4[T interface{ String() string}](arg T) {} // Valid
Quotes from The Go Programming Language Specification Version of December 15, 2022