英文:
How do you access certain parts of an array with type []interface{} in Go?
问题
我有一个包含字符串键和不同类型值的映射,打印出来的样子是这样的:
map[command:ls count:[1 1]]
当对 count 使用 reflect.TypeOf
进行检查时,返回的类型是 []interface{}
。我无法通过索引访问这些值,如果我尝试将其传递给一个接受 []interface{}
类型参数的函数,它会报告我试图传递一个类型为 interface{}
的值。
我想在这个例子中访问 count,它应该有两个值,即 1
和 1
。
英文:
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
.
答案1
得分: 6
你需要区分类型和底层类型。你的映射类型是 map[string]interface{}
。这意味着 count
的值是 interface{}
类型,其底层类型是 []interface{}
。因此,你不能将 count
作为 []interface{}
类型传递。在使用它作为数组之前,你需要进行类型断言。每个项目的类型将是 interface{}
,可以进一步断言为 int
(根据你的数据似乎是这样)。
示例:
count := m["count"].([]interface{})
value1 := count[0].(int)
value2 := count[1].(int)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论