首頁 > 後端開發 > 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學習者快速成長!