Setting pointers using reflect.

2,980 views
Skip to first unread message

Paul Borman

unread,
Sep 7, 2011, 1:45:58 PM9/7/11
to golang-nuts
I am trying to build up a structure using reflect.  Most of it is fine, but not when it comes to elements that have pointers.

In my code I would like to have:

    switch v.Kind() {
    case reflect.Ptr:
        val := reflect.New(v.Type().Elem())
        v.Set(val)
    ...
    }

which yields

    panic: reflect.Value·Set using unaddressable value

v was obtained as follows:

    s := &struct{P *int}
    v := reflect.ValueOf(s).Elem().Field(0)

so initially v is a nil pointer.  What is the correct way, using reflect, to create an new value to assign to a pointer?

Thanks,

    -Paul

Kyle Lemons

unread,
Sep 7, 2011, 2:15:29 PM9/7/11
to Paul Borman, golang-nuts

Paul Borman

unread,
Sep 7, 2011, 2:36:47 PM9/7/11
to Kyle Lemons, golang-nuts
Well look at that.  I had simplified the code in my email from a larger test case.  Shame on me for not building the full small test case.  It appears my actual bug was not the Set but when I was trying to fill the contents of val that was being set to v.

Thanks Kyle,

    -Paul
Reply all
Reply to author
Forward
0 new messages