Calling Methods on Union Constraints in Go Generics
In Go generics (v1.18), you can encounter a type union constraint that limits the parameter type to types implementing a unified interface. However, the inability to call shared methods among the constrained types raises concerns about the utility of such constraints.
Consider the following code:
type A struct {} type B struct {} type AB interface { *A | *B } func (a *A) some() bool { return true } func (b *B) some() bool { return false } func some[T AB](x T) bool { return x.some() } // Compiler error
The compiler error "x.some undefined" is due to the fact that the type union constraint *A | *B does not guarantee the existence of a some method on both *A and *B.
To resolve this issue, you can add the method to the interface constraint:
type AB interface { *A | *B; some() bool } func some[T AB](x T) bool { return x.some() } // Works
This restricts T to types that implement both *A or *B and declare the some method.
However, this solution is seen as a workaround for what should ideally work with type unions alone. Go 1.18 currently has limitations where the compiler supports calling a method on a value of type parameter P only if the method m is explicitly declared by P's constraint interface. Despite the language specifications stating that the method set of an interface is the intersection of the method sets of each type in the interface's type set. This issue is expected to be addressed in Go 1.19.
The above is the detailed content of Can Go Generics' Union Constraints Call Shared Methods Without Explicit Interface Declaration?. For more information, please follow other related articles on the PHP Chinese website!