如何从 nil 指针创建值
Feb 09, 2024 am 10:50 AMphp小编柚子为您介绍如何从 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
有关更多信息,请参阅文档:
-
reflect.TypeOf
获取指定值的类型信息 -
reflect.Type.Elem
获取类型的元素类型 -
reflect.New
返回指向指定类型零值的指针 -
reflect.Value.Interface
返回值作为接口{} -
v.(T)
类型断言
以上是如何从 nil 指针创建值的详细内容。更多信息请关注PHP中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章
击败分裂小说需要多长时间?
3 周前
By DDD
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章
击败分裂小说需要多长时间?
3 周前
By DDD
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章标签

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)