Home > Blockchain >  go reflect: how to dynamically create a pointer to a pointer to ...?
go reflect: how to dynamically create a pointer to a pointer to ...?

Time:12-04

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...

CodePudding user response:

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
  • Related