首頁 > 後端開發 > 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學習者快速成長!