2

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

TheDiveO
  • 2,183
  • 2
  • 19
  • 38

1 Answers1

4

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
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • I'm amazed at how simple this is, the key is `p.Elem().Set()`! Thank you very much for this super quick solution! – TheDiveO Dec 03 '21 at 20:22