dictionary - 无法访问 [] 接口(interface)内 map 中的键

标签 dictionary go interface

示例代码:

package main

import "fmt"

func main() {
    example_container := []interface{}{
        map[string]string{
            "name": "bob",
            "id": "1",
        },
        map[string]string{
            "name": "jim",
            "id": "2",
        },
    }
    fmt.Printf("%v\n", example_container)
    fmt.Printf("%v\n", example_container[0])
    fmt.Printf("%v\n", example_container[0]["name"])
}

问题行:

fmt.Printf("%v\n", example_container[0]["name"])

错误:

invalid operation: example_container[0]["name"] (type interface {} does not support indexing)

问题:

那么我如何访问这个界面中的键呢?

我是否必须定义一个带有方法集的更精细的接口(interface)来完成此操作?

最佳答案

由于您的 slice 类型是 []interface{},索引此 slice 将为您提供 interface{} 类型的元素。 interface{} 类型的值无法编入索引。

但由于您将 map[string]string 类型的值放入其中,您可以使用 type assertion获取该 map 类型的值,您可以对其进行正确索引:

fmt.Printf("%v\n", example_container[0].(map[string]string)["name"])

输出(在 Go Playground 上尝试):

[map[name:bob id:1] map[name:jim id:2]]
map[name:bob id:1]
bob

如果您知道您将始终在您的 example_container slice 中存储 map[string]string 类型的值,最好是这样定义它:

example_container := []map[string]string{
    map[string]string{
        "name": "bob",
        "id":   "1",
    },
    map[string]string{
        "name": "jim",
        "id":   "2",
    },
}

然后你不需要类型断言来访问名称:

fmt.Printf("%v\n", example_container[0]["name"])

Go Playground 上试试这个.

另请注意,在用于初始化 example_container slice 的复合文字中,您甚至可以在列出元素时省略映射类型:

example_container := []map[string]string{
    {
        "name": "bob",
        "id":   "1",
    },
    {
        "name": "jim",
        "id":   "2",
    },
}

关于dictionary - 无法访问 [] 接口(interface)内 map 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41608942/

相关文章:

Java:使用传递接口(interface)参数的方法实现接口(interface)

inheritance - 用于约束和继承集的接口(interface)

python - 如何在一行for循环内的字典中添加另一个属性

go - fmt.Println 打印出像 %s 这样的格式动词

go - 如何在 Go 中表示货币?

linux - 生成核心转储

为返回 char* 的 C 函数创建 FORTRAN 接口(interface)

Python 将字典的值分配给列表

c# - 使用时间跨度作为字典中的键?

ios - Swift - 如何从值中获取字典元素的索引?