在 Go 語言參考中,關于型別引數宣告的部分,我將[P Constraint[int]]其視為型別引數示例。
這是什么意思?如何在通用函式定義中使用此結構?
uj5u.com熱心網友回復:
它是一個型別引數串列,如您鏈接的段落中所定義,它具有一個型別引數宣告,該宣告具有:
P作為型別引數名稱Constraint[int]作為約束
而是泛型型別Constraint[int]的實體化(您必須始終在使用時實體化泛型型別)。
在語言規范的那一段中,Constraint沒有定義,但它可以合理地是一個通用介面:
type Constraint[T any] interface {
DoFoo(T)
}
type MyStruct struct {}
// implements Constraint instantiated with int
func (m MyStruct) DoFoo(v int) {
fmt.Println(v)
}
您可以像使用任何型別引數約束一樣使用它:
func Foo[P Constraint[int]](p P) {
p.DoFoo(200)
}
func main() {
m := MyStruct{} // satisfies Constraint[int]
Foo(m)
}
游樂場:https ://go.dev/play/p/aBgva62Vyk1
這個約束的使用顯然是人為的:你可以簡單地使用那個實體化的介面作為引數的型別。
更多關于泛型介面的實作細節可以參考:如何實作泛型介面?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494525.html
