我想了解 go1.18 中的泛型實現。在我的測試示例中,我存儲了一系列測試用例并嘗試調用一個函數變量。不幸的是,當我嘗試使用變量tc.input時EvalCases函數出現錯誤,我收到以下錯誤:不能使用輸入(受 Inputer 約束的 T 類型變量)作為 fn 參數中的字符串類型為什么我會收到該錯誤,我該如何解決?import ( "fmt" "strconv")type BoolCase func(string) booltype Inputer interface { int | float64 | ~string}type Wanter interface { Inputer | bool}type TestCase[T Inputer, U Wanter] struct { input T want U}type TestConditions[T Inputer, U Wanter] map[string]TestCase[T, U]// IsNumeric validates that a string is either a valid int64 or float64func IsNumeric(s string) bool { _, err := strconv.ParseFloat(s, 64) return err == nil}func EvalCases[T Inputer, U Wanter](cases TestConditions[T, U], fn BoolCase) { for name, tc := range cases { input := T(tc.input) want := tc.want // Error: cannot use input (variable of type T constrained by Inputer) as type string in argument to fn got := fn(input) fmt.Printf("name: %-20s | input: %-10v | want: %-10v | got: %v\n", name, input, want, got) }}func main() { var cases = TestConditions[string, bool]{ "empty": {input: "", want: false}, "integer": {input: "123", want: true}, "float": {input: "123.456", want: true}, } fn := IsNumeric EvalCases(cases, fn)}
1 回答

莫回無
TA貢獻1865條經驗 獲得超7個贊
為什么我會收到該錯誤
因為fn
是 a BoolFunc
,它是 a func(string) bool
,因此需要 astring
作為參數,但是input
類型是T
。此外,根據您的定義,T
滿足Inputer
約束,因此也可以假定類型int
,float64
或任何具有基礎類型 ( ) 的非string
類型,其中沒有一個隱式轉換為。string
~string
string
我如何解決它?
您需要將其定義更改BoolCase
為其一個參數具有泛型類型參數。您可以將其限制為Inputer
,但也可以使用any
( interface{}
)。
type BoolCase[T any] func(T) bool
然后確保在函數的簽名中提供這個泛型類型參數EvalCases
:
func EvalCases[T Inputer, U Wanter](cases TestConditions[T, U], fn BoolCase[T])
https://go.dev/play/p/RdjQXJ0WpDh
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消