php editor Youzi will introduce you how to create a value from a nil pointer. In programming, a nil pointer is a pointer that does not point to any valid memory address. Normally, we cannot create a value from a nil pointer because it does not point to any valid memory space. However, some programming languages provide special handling that allows us to create values from nil pointers. In this article, we'll discuss how to handle this particular situation and how to avoid potential problems and errors. Whether you are a beginner or an experienced developer, this article will provide you with helpful guidance and advice.
In Go 1.19, consider the following definition:
type A struct{} type B struct{} type Field interface { *A | *B } type Person[T Field] struct { field T }
Given a nil Field
, can I dynamically create its underlying value?
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://www.php.cn/link/ccd2d123f4ec4d777fc6ef757d0fb642
For more information, see the documentation:
reflect.TypeOf
Get the type information of the specified valuereflect.Type.Elem
Get the element type of the type
reflect.New
Returns a pointer to a zero value of the specified type
reflect.Value.Interface
Return value as interface{} v.(T)
Type assertionThe above is the detailed content of How to create a value from a nil pointer. For more information, please follow other related articles on the PHP Chinese website!