Go Generics: Unlocking Shared Methods in Type Unions
In Go's new generic feature, the type union constraint allows multiple types to be bound to a single generic type parameter. However, the question arises: how can shared methods be utilized across these types?
Initial Attempt and Compiler Error
<br>type AB interface {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">*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() // undefined
}
The above code attempts to use the shared some method in function some, but encounters an error, as the compiler cannot determine which some method to call.
Workaround using Interface Constraint
To overcome this limitation, the shared method can be added directly to the interface constraint:
<br>type AB interface {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">*A | *B some() bool
}
func some[T AB](x T) bool {
return x.some() // works
}
This ensures that the generic type T must satisfy the interface constraint, which includes the some method.
Limitation in Go 1.18
It's important to note that this workaround is a temporary measure due to a restriction in Go 1.18. The Go specifications allow for shared methods to be used in type unions, but the current compiler implementation limits it to methods explicitly declared in the constraint interface.
Resolution in Go 1.19
The Go 1.18 release notes acknowledge this limitation and express plans to remove it in Go 1.19, allowing for direct access to shared methods in type unions. This improvement will enhance the expressiveness and flexibility of Go generics.
The above is the detailed content of How Can Shared Methods Be Used with Go Generics' Type Union Constraints?. For more information, please follow other related articles on the PHP Chinese website!