這曾經在 go1.18beta1 中有效,但在 go1.18rc1 中無效
package main
type A struct{}
func (*A) Hello() {
println("Hello")
}
func Create[M any, PT interface {
Hello()
*M
}](n int) (out []*M) {
for i := 0; i < n; i {
v := PT(new(M))
v.Hello()
out = append(out, v)
}
return
}
func main() {
println(Create[A](2))
}
執行會拋出
./prog.go:16:21: cannot use v (variable of type PT constrained by interface{Hello(); *M}) as type *M in argument to append:
PT does not implement *M (type *M is pointer to interface, not interface)
似乎是由于這個限制:
不允許將型別引數或指向型別引數的指標作為未命名欄位嵌入到結構型別中。同樣,不允許在介面型別中嵌入型別引數。目前還不清楚這些是否會被允許。
我怎樣才能在 go1.18rc1 中做到這一點?
uj5u.com熱心網友回復:
您必須再次轉換v回*M。
out = append(out, (*M)(v))
你得到的錯誤是關于可分配性的。實際上,您問題中的參考并不禁止在 interface 中嵌入指標型別。兩者M和PT都是不同的命名型別引數,如果沒有顯式轉換,您不能將一個分配給另一個。
相反,轉換是有效的,因為PT的型別集中的所有型別(僅*M)都可以轉換為*M.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/443007.html
上一篇:在嵌套函式中設定值
