This人曾在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)

似乎是由于这个限制:

不允许将类型参数或指向类型参数的指针作为未命名字段嵌入 struct 类型中.同样,不允许在接口类型中嵌入类型参数.目前尚不清楚这些措施是否会被允许.

在go1我该怎么做.18rc1?

推荐答案

你必须再次将v转换回*M.

out = append(out, (*M)(v))

我相信你犯的错误是关于可分配性的.MPT都是不同的命名类型参数,如果不进行显式转换,就无法将一个参数指定给另一个参数.

这种转换是有效的,因为PT的类型集(只有*M个)中的所有类型都可以转换为*M.

Go相关问答推荐

如何在Deliverq中高效地传达客户依赖关系?

Gorm foreign 密钥

如何在GoFr中为生产和本地环境设置不同的配置?

JWT 如何解析声明有效性和错误?

无法读取postman 中的表单数据

Go:如何在不加载正文的情况下创建 http 代理通行证

Go test "-run -" 标志执行测试更快

golang / urfave.cli:无法手动设置标志

此 Golang 程序中的同步问题

Go 切片容量增长率

无法使用 gocsv 读取引用字段

如何在自定义验证函数中获取 struct 名称

Golang - 客户 Unmarshaler/Marshaler 在指针上具有 nil/null 值

对所有标志进行 ORing 的简短方法

Golang:隐式 struct 匹配

panic :拨号 tcp:在 172.22.64.1:53 上查找 bookstoreDB:没有这样的主机

如何在 Golang 中使用具有相同名称或特定关键字的行或列重新排列/排序 CSV

Golang ACMEv2 HTTP-01 挑战不挑战服务器

通用函数与外部包中的常见成员一起处理不同的 struct ?

Unescape 在 rss 中两次逃脱了标题