Home  >  Article  >  Backend Development  >  How to create a value from a nil pointer

How to create a value from a nil pointer

PHPz
PHPzforward
2024-02-09 10:50:09967browse

如何从 nil 指针创建值

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.

Question content

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

  }
}

Solution

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:

The 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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete