卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34662本站已运行393

如何从 nil 指针创建值

如何从 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

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

  • reflect.TypeOf获取指定值的类型信息
  • reflect.Type.Elem 获取类型的元素类型
  • reflect.New 返回指向指定类型零值的指针
  • reflect.Value.Interface 返回值作为接口{}
  • v.(T) 类型断言
卓越飞翔博客
上一篇: 如何附加到元素类型不是golang中命名类型的切片
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏