Type parameter restrictions
May 2, 2023
We’ll get to a full discussion of type parameters later on, but knowing at least what they look like is useful for the next section. So here’s an example, used in the definition of a generic function:
func min[T ~int|~float64](x, y T) T {
In this example, min[T ~int|~float64]
represents the type parameter.
With that in mind…
General interfaces
…
The type
T
in a term of the formT
or~T
cannot be a type parameter, and the type sets of all non-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty). Given a type parameterP
:interface { P // illegal: P is a type parameter int | ~P // illegal: P is a type parameter ~int | MyInt // illegal: the type sets for ~int and MyInt are not disjoint (~int includes MyInt) float32 | Float // overlapping type sets but Float is an interface }
This means, for example, that within our above min
function, the following would be illegal:
func min[T ~int|~float64](x, y T) T {
var x interface {
T // illegal because T is a type parameter of the generic function
}
We also can’t combine types and underlying types that overlap. At least this restriction doesn’t require any special understanding of generics that we haven’t covered yet.
type MyInt int
interface {
~int | MyInt // Illegal becasue of overlapping type sets
}
Quotes from The Go Programming Language Specification Version of December 15, 2022