I'm trying to iterate through the interface
dialogCommands
that is a slice
. I can iterate through it normally, and the Println
into each Index
gives me a map
. However, this map
is being printed as having type struct
if reflect.TypeOf(dialogCommands).Kind() == reflect.Slice {
commands := reflect.ValueOf(dialogCommands)
for i:=0; i<commands.Len(); i++ {
v := commands.Index(i)
fmt.Println(reflect.TypeOf(v).Kind())
fmt.Println(v)
}
The output from this is
struct
map[options:[a b c]]
struct
map[startDialogs:[dialog1]]
As you can see, the type is a struct
but the output is a map
. How to iterate through the keys
of v
? I cannot just treat this a map because it's of type reflect.Value
, so I need a way to iterate through it, but as you see, the kind
is struct
while the Println
says it's a map
Update:
Here's the Dialog
structure
type Dialog struct {
Dialog bson.Raw `json:"dialog" bson:"dialog"`
}
and remember that dialogCommands
gets unmarshaled into interface{}
[map[options:[a b c]] map[startDialogs:[dialog1]]]
The expression reflect.TypeOf(v).Kind()
returns the kind of v
, not of the underlying value in v
. The variable v has type reflect.Value
. This is a struct type.
The following print statements will print what you expect assuming that dialogCommands
is a slice of maps:
fmt.Println(v.Kind()) // prints the kind of v's underlying value
fmt.Println(v) // prints v's underlying value
Based on your comment on this question, it looks like dialogCommands
is a slice of interfaces. If so, then you will want to work with the interface's element:
if v.Kind() == reflect.Interface {
v = v.Elem()
}
fmt.Println(v.Kind())
fmt.Println(v)