首頁  >  文章  >  後端開發  >  具有方法作為泛型函數的類型約束的接口

具有方法作為泛型函數的類型約束的接口

王林
王林轉載
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刪除