这过去在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中做到这一点?
发布于 2022-03-11 15:52:21
您必须再次将v转换回*M。
out = append(out, (*M)(v))你犯的错误是关于可转让性的。事实上,问题中的引号并不禁止在接口中嵌入指针类型。M和PT都是不同的命名类型参数,如果没有显式转换,就不能将其中一个分配给另一个。
相反,转换是有效的,因为PT类型集中的所有类型(只有*M)都可以转换为*M。
https://stackoverflow.com/questions/71440697
复制相似问题