英文:
An interface with methods as type constraint for generic function
问题
我正在尝试在编写一个用于测试的断言函数时使用泛型,但是它给我一个错误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: %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{})
// 错误: "Some does not implement TestUtilT (wrong type for method Equals...)"
}
英文:
I am trying to make use of generics when writing an asserting function for testing things however it gives me an error Some does not implement TestUtilT (wrong type for method Equals...)
error. How can I make code bellow work if at all?
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...)"
}
答案1
得分: 3
替换为
func (s *Some) Equals(other TestUtilT) bool {
然后替换为
Assert[Some](t, "", &Some{}, &Some{})
第一个更改将修复您的初始错误消息,但是如果没有第二个更改,您的代码仍然无法正常工作。
英文:
Replace
func (s *Some) Equals(other Some) bool {
with
func (s *Some) Equals(other TestUtilT) bool {
Then replace
Assert[Some](t, "", Some{}, Some{})
with
Assert[Some](t, "", &Some{}, &Some{})
The first change will fix your initial error message, but your code will still not work without the second change as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论