英文:
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 := "It's full of stars!"
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()) // prints **********string
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论