在 Go Language reference 中,關于Type parameter declarations的部分,我看到[P Constraint[int]]了一個類型參數示例。這是什么意思?如何在通用函數定義中使用此結構?
2 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
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
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消