go reflect: how to dynamically create a pointer to a pointer to …?

huangapple go评论72阅读模式
英文:

go reflect: how to dynamically create a pointer to a pointer to ...?

问题

我想创建一个表示多级嵌套指向最终值的reflect.Value。嵌套级别在编译时是未知的。如何使用reflect创建指向指针的指针?

当我尝试创建指向指针的指针时,我已经遇到了"不可寻址的值"障碍。

dave := "It's full of stars!"
stargazer := reflect.ValueOf(&dave)
stargazer = stargazer.Addr() // 报错:reflect.Value.Addr of unaddressable value

对于stargazer.UnsafeAddr()等也是一样。虽然stargazer.Elem().UnsafeAddr()等可以工作,但我看不出这如何帮助(递归地)创建一个新的非零指向指针的指针...

英文:

I would like to create a reflect.Value that represents a multiple-level nested pointer to a final value. The nesting level is not known at compile time. How can I create pointers to pointers using reflect?

I already stumble at the "unaddressable value" hurdle when trying to create a pointer to a pointer.

dave := "It's full of stars!"
stargazer := reflect.ValueOf(&dave)
stargazer = stargazer.Addr() // panic: reflect.Value.Addr of unaddressable value

Same for stargazer.UnsafeAddr(), etc. While stargazer.Elem().UnsafeAddr() etc. works, I can't see how this helps in (recursively) creating a new non-zero pointer to a pointer...

答案1

得分: 4

使用以下代码来创建指向stargazer值的指针。

p := reflect.New(stargazer.Type())
p.Elem().Set(stargazer)
// p.Interface() 是指向 stargazer.Interface() 值的指针

示例:

dave := "它充满了星星!"
stargazer := reflect.ValueOf(dave)
for i := 0; i < 10; i++ {
    p := reflect.New(stargazer.Type())
    p.Elem().Set(stargazer)
    stargazer = p
}
fmt.Printf("%T\n", stargazer.Interface()) // 输出 **********string

请注意,这只是代码的翻译部分,不包括任何其他回答或问题。

英文:

Use the following code to create a pointer to the value in stargazer.

p := reflect.New(stargazer.Type())
p.Elem().Set(stargazer)
// p.Interface() is a pointer to the value stargazer.Interface()

Example:

dave := &quot;It&#39;s full of stars!&quot;
stargazer := reflect.ValueOf(dave)
for i := 0; i &lt; 10; i++ {
	p := reflect.New(stargazer.Type())
	p.Elem().Set(stargazer)
	stargazer = p
}
fmt.Printf(&quot;%T\n&quot;, stargazer.Interface()) // prints **********string

huangapple
  • 本文由 发表于 2021年12月4日 04:06:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/70220096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定