簡體   English   中英

以方法作為泛型類型約束的接口 function

[英]An interface with methods as type constraint for generic function

我在編寫斷言 function 進行測試時嘗試使用 generics 但是它給了我一個錯誤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{})

第一次更改將修復您的初始錯誤消息,但如果沒有第二次更改,您的代碼仍然無法正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM