卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34176本站已运行391

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

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

问题内容

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

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

卓越飞翔博客
上一篇: 如何使用名称具有包名称的嵌套结构来启动 go 结构
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏