在 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 关注
- 149 浏览
添加回答
举报
0/150
提交
取消