在 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 = ?
}
}
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
有关更多信息,请参阅文档:
reflect.TypeOf
获取指定值的类型信息reflect.Type.Elem
获取类型的元素类型reflect.New
返回指向指定类型零值的指针reflect.Value.Interface
返回值作为接口{}v.(T)
类型断言