【问题标题】:how access to keys in map[interface{}] interface{}如何访问 map[interface{}] interface{} 中的键
【发布时间】:2017-01-07 00:07:49
【问题描述】:

这是我的 yaml 文件:

db:
    # table prefix
    tablePrefix: tbl

    # mysql driver configuration
    mysql:
        host: localhost
        username: root
        password: mysql

    # couchbase driver configuration
    couchbase:
        host: couchbase://localhost

我使用 go-yaml 库将 yaml 文件解组为变量:

config := make(map[interface{}]interface{})
yaml.Unmarshal(configFile, &config)

配置值:

map[mysql:map[host:localhost username:root password:mysql]      couchbase:map[host:couchbase://localhost] tablePrefix:tbl]

如何在没有预定义结构类型的情况下访问配置中的 db -> mysql -> 用户名

【问题讨论】:

  • 请举例说明。您提供的代码有效,不会导致此错误。
  • 我更新了我的问题@jimb

标签: go yaml


【解决方案1】:

YAML 使用字符串键。你试过了吗:

config := make(map[string]interface{})

要访问嵌套属性,请使用type assertions

mysql := config["mysql"].(map[string][string])
mysql["host"]

一种常见的模式是为通用映射类型设置别名。

type M map[string]interface{}

config := make(M)
yaml.Unmarshal(configFile, &config)
mysql := config["mysql"].(M)
host := mysql["host"].(string)

【讨论】:

  • 我有一个动态配置文件,可能涉及数组值
  • “gopkg.in/yaml.v2”包的默认类型是map[interface{}]interface{}
【解决方案2】:

如果你没有提前定义类型,你需要从你遇到的每个interface{}assert 正确的类型:

if db, ok := config["db"].(map[interface{}]interface{}); ok {
    if mysql, ok := db["mysql"].(map[interface{}]interface{}); ok {
        username := mysql["username"].(string)
        // ...
    }
}

https://play.golang.org/p/koSugTzyV-

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2021-08-30
    • 2018-08-05
    • 2015-01-14
    • 2022-12-01
    • 2017-07-13
    • 2015-05-02
    • 2016-08-06
    • 2016-02-27
    相关资源
    最近更新 更多