我试图在编写断言函数来测试事物时使用泛型,但是它给了我一个错误 some does not implement testutilt (wrong type for method equals...)
错误。如果有的话我怎样才能使下面的代码工作?
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: %sn",
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...)"
}
正确答案
替换
func (s *some) equals(other some) bool {
与
func (s *some) equals(other testutilt) bool {
然后替换
assert[some](t, "", some{}, some{})
与
Assert[Some](t, "", &Some{}, &Some{})
第一个更改将修复您的初始错误消息,但如果没有第二个更改,您的代码仍然无法工作。