首页 > 后端开发 > Golang > 正文

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

王林
发布: 2024-02-06 09:45:11
转载
936 人浏览过

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

问题内容

我试图在编写断言函数来测试事物时使用泛型,但是它给了我一个错误 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!