一个具有方法作为类型约束的接口,用于泛型函数。

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月2日 01:36:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75314055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定