在 Golang 中,从 nil 指针创建一个值

问题描述 投票:0回答:1

在 Go 1.19 中,考虑以下定义:

type A struct{}
type B struct{}

type Field interface {
    *A | *B
}

type Person[T Field] struct {
    field T
}

给定一个 nil

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 = ?

  }
}
go pointers
1个回答
1
投票
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


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

© www.soinside.com 2019 - 2024. All rights reserved.