yoad w
yoad w

Reputation: 325

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

Upvotes: 0

Views: 518

Answers (1)

Mostafa Solati
Mostafa Solati

Reputation: 1235

No need to double reflection , you can iterate SysVars like this :

p := &Configuration{
SysVars :[]string{"a","b","c"},
}

s:= reflect.ValueOf(p).Elem().FieldByName("SysVars")
for i:=0 ; i< s.Len() ; i++ {
   fmt.Println(s.Index(i).String())
}

Upvotes: 3

Related Questions