lundi 5 octobre 2020

setting nil pointer's address with reflections

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





Aucun commentaire:

Enregistrer un commentaire