vendredi 14 août 2020

panic: reflect: call of reflect.Value.FieldByName on interface Value

I have variable of type interface{} and I want to change value of field using reflection. I have variable of type interface{} and I want to change value of field using reflection. How can I do it? Variable must be of type interface{} due to other requirements. If variable isn't of type interface{} all works, otherwise code throws

reflect: call of reflect.Value.FieldByName on interface Value

my code

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := struct {
        Name string
    }{}

    // works
    reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
    fmt.Printf("%#v\n", a)

    var b interface{}
    b = struct {
        Name string
    }{}
    // panics
    reflect.ValueOf(&b).Elem().FieldByName("Name").SetString("Hello")
    fmt.Printf("%#v\n", b)
}





Aucun commentaire:

Enregistrer un commentaire