首页 > 后端开发 > Golang > 正文

如何从 nil 指针创建值

PHPz
发布: 2024-02-09 10:50:09
转载
967 人浏览过

如何从 nil 指针创建值

php小编柚子为您介绍如何从 nil 指针创建值。在编程中,nil 指针是指一个未指向任何有效内存地址的指针。通常情况下,我们无法从 nil 指针创建值,因为它不指向任何有效的内存空间。然而,有些编程语言提供了特殊的处理方式,允许我们从 nil 指针创建值。在这篇文章中,我们将讨论这种特殊情况下的处理方法,以及如何避免潜在的问题和错误。无论您是初学者还是有经验的开发者,本文都将为您提供有用的指导和建议。

问题内容

在 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://www.php.cn/link/ccd2d123f4ec4d777fc6ef757d0fb642

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

以上是如何从 nil 指针创建值的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!