In Go2 generics, as of current draft, I can specify a type constraint on a generic type using an interface.
import "fmt"
type Stringer interface {
String() string
}
func Print[T Stringer](value T) {
fmt.Println(value.String())
}
This way, I can specify, that the type must implement a method. However, I don't see any way to force the implementation of a method, with itself having an argument of the generic type.
type Lesser interface {
Less(rhs Lesser) bool
}
type Int int
func (lhs Int) Less(rhs Int) bool {
return lhs < rhs
}
func IsLess[T Lesser](lhs, rhs T) bool {
return lhs.Less(rhs)
}
func main() {
IsLess[Int](Int(10), Int(20))
}
Exits with
Int does not satisfy Lesser: wrong method signature
got func (Int).Less(rhs Int) bool
want func (Lesser).Less(rhs Lesser) bool
The original draft with contracts would make this possible, but not the new draft.
It can also be done with the following, but that would leave you with repeating the same constraint over and over again, braking DRY (and DRY code is the purpose of generics). It would also make the code much more unwieldy if the desired interfaces have multiple methods.
func IsLess[T interface { Less(T) bool }](lhs, rhs, T) bool {
return lhs.Less(rhs)
}
Is there any way to do this with a predefined interface in the new draft?