lundi 24 décembre 2018

reflecting array inside interface

I'm trying to access via reflection an array within an interface.

Among other fields, I also have an array of strings:

type Configuration struct {
    ...
    SysVars []string
}

I can access the field SysVars like this:

elem := reflect.ValueOf(conf).Elem()
sysVarsInterface := elem.FieldByName("SysVars").Interface()

By this point, when using the GoLand's debugger I can see that sysVarsInterface is an interface with the two values I'm expecting. Since it's an array, I assume I need to treat it as interface and reflect it again? so it looks like this:

sysVarsValue := reflect.ValueOf(&sysVarsInterface)
sysVarsElem := sysVarsValue.Elem()

but iterating over it fails:

for i:=0; i< sysVarsElem.NumField(); i++ {
    vname := sysVarsElem.Type().Field(i).Name
    fmt.Println(vname)
}

saying:

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

any ideas what am I doing wrong?
I was using this as a reference





Aucun commentaire:

Enregistrer un commentaire