首页  >  文章  >  后端开发  >  具有方法作为泛型函数的类型约束的接口

具有方法作为泛型函数的类型约束的接口

王林
王林转载
2024-02-06 09:45:11941浏览

具有方法作为泛型函数的类型约束的接口

问题内容

我试图在编写断言函数来测试事物时使用泛型,但是它给了我一个错误 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{}) 
    // 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{})

第一个更改将修复您的初始错误消息,但如果没有第二个更改,您的代码仍然无法工作。

以上是具有方法作为泛型函数的类型约束的接口的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除