I have a map with string keys and different types for values, when printing it looks like this:
map[command:ls count:[1 1]]
When checking reflect.TypeOf
on the count it returns type []interface{}
. I cannot access the values by index, and if I try passing it into a function that accept a param of type []interface{}
it claims that I'm tying to pass a value of type interface{}
I would like to access the count in this example which would be 2 values. 1
and 1
.
You have to differentiate type and underlying type. Your map is of the type map[string]interface{}
. Which means that the value for count
is of type interface{}
, and its underlying type if []interface{}
. So you can't pass the count as a type []interface{}
. You have do a type assertion it before using it as an array. Every item will then of type interface{}
, which can in turn be asserted as int
(as it seem your data is).
Example:
count := m["count"].([]interface{})
value1 := count[0].(int)
value2 := count[1].(int)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.