Home >Backend Development >Golang >Interface with type constraints for methods as generic functions
I am trying to use generics while writing an assertion function to test things, but it gives me an errorsome does not implement testutilt (wrong type for method equals...)
Error. If so how can I make the code below work?
package test_util import ( "fmt" "testing" ) type TestUtilT interface { Equals(TestUtilT) bool String() string } func Assert[U TestUtilT](t *testing.T, location string, must, is U) { if !is.Equals(must) { t.Fatalf("%s expected: %s got: %s\n", fmt.Sprintf("[%s]", location), must, is, ) } } type Some struct { } func (s *Some) Equals(other Some) bool { return true } func (s *Some) String() string { return "" } func TestFunc(t *testing.T) { Assert[Some](t, "", Some{}, Some{}) // Error: "Some does not implement TestUtilT (wrong type for method Equals...)" }
Replace
func (s *some) equals(other some) bool {
and
func (s *some) equals(other testutilt) bool {
Then replace
assert[some](t, "", some{}, some{})
and
Assert[Some](t, "", &Some{}, &Some{})
The first change will fix your initial error message, but your code still won't work without the second change.
The above is the detailed content of Interface with type constraints for methods as generic functions. For more information, please follow other related articles on the PHP Chinese website!