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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3