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

How to create a value from a nil pointer

PHPz
Release: 2024-02-09 10:50:09
forward
1010 people have browsed it

如何从 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
}
Copy after login

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

  }
}
Copy after login

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
    }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template