在GO 1.19中,请考虑以下定义:

type A struct{}
type B struct{}

type Field interface {
    *A | *B
}

type Person[T Field] struct {
    field T
}

假设零值为Field,我可以动态地创建其潜在价值吗?

func (p Person[T]) do() {
  if p.field == nil {

    // Can I make a value here that will be *A or *B dynamically depending on T?
    // Something that would be equivalent to new(A) or new(B)
    p.field = ?

  }
}

推荐答案

func (p Person[T]) do() {
    if p.field == nil {
        // assuming T is a pointer type, e.g. *A
        pp := new(T)             // initialize an instance of **A
        rt := reflect.TypeOf(pp) // get the reflect.Type representation of **A
        rt = rt.Elem()           // get the reflect.Type representation of *A
        rt = rt.Elem()           // get the reflect.Type representation of A
        rv := reflect.New(rt)    // initialize reflect.Value representation of *A
        v := rv.Interface()      // get the interface{}(*A) instance from reflect.Value
        t := v.(T)               // type assert the interface's dynamic type
        p.field = t
    }
}

https://go.dev/play/p/GtnL3WcnB1E


有关更多信息,请参阅文档:

Go相关问答推荐

使用恶意软件 scanner (ClamAV)时的Google云存储桶上传文件验证

Zitadel示例Go Webapp加密密钥

日志(log)文件不在 golang 的日志(log)目录中

当我有外键时,如何使用 GORM 创建数据库的新条目

Caddy服务器try 打开端口80而不是8090.

GitHub 中 REST API 的 aws 凭证问题

如何在 gocql 中设置最大池大小?

如何使用泛型将接口转换为指定类型

具有未导出字段的 struct 类型之间的转换

在 Golang 中,如何将接口作为泛型类型与 nil 进行比较?

为什么此代码在运行命令 error="exec: not started" 时出现错误?

具有近似约束的函数值导致的实例化失败

将未知长度切片的值分配给Go中的 struct ?

跟踪长时间运行的任务的进度 - 正确的方法

为什么我不能使用来自 gocloak 中 Login() 的访问令牌在 KeyCloak 中创建新客户端?

如何使用golang操作很长的字符串以避免内存不足

递归数据 struct 解组在 Go Lang Protobuf 中给出错误无法解析无效的线格式数据

如何使用带有Electron 表格 ID、Electron 表格名称、表格 ID 和值的 golang 在 googlesheet 中插入数据

go mod tidy 错误消息:但是 go 1.16 会 Select

如何使用 fyne 避免 GUI 应用程序中的循环依赖?