setting nil pointer's address with reflections

Viewed 111

I'm writing Go Application and I'm trying to find out how to create a nil pointer with reflection and to set it's value.

I created a small code to demonstrate what I'm trying to achieve:

package main

import (
    "log"
    "reflect"
)

func main() {
    var myV *int
    v := reflect.ValueOf(myV)
    t := reflect.TypeOf(myV)
    myP := reflect.New(t.Elem())
    myP.Elem().SetInt(5)
    v.Set(myP) <-- PANIC HERE
    log.Print(v.Interface())
}

so here I declare an int pointer variable, and I use reflection to create a new instance and to set the pointer to that address but I fail in setting the pointer address.

i get the error:

panic: reflect: reflect.Value.Set using unaddressable value

what am I doing wrong ?

thanks

1 Answers

ok thnkas to @mkopriva's comment I was able to resolve it. thanks a lot :)

var myV *int
v := reflect.ValueOf(&myV)
t := reflect.TypeOf(myV)
myP := reflect.New(t.Elem())
myP.Elem().SetInt(5)
v.Elem().Set(myP)
Related