Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading