Go 如何访问map[interface{}]interface{}中的键
这是我的yaml文件:Go 如何访问map[interface{}]interface{}中的键,go,yaml,Go,Yaml,这是我的yaml文件: db: # table prefix tablePrefix: tbl # mysql driver configuration mysql: host: localhost username: root password: mysql # couchbase driver configuration couchbase: host: couchbase:/
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]
如何在没有预定义结构类型的情况下访问config中的db->mysql->username值YAML使用字符串键。您是否尝试过:
config := make(map[string]interface{})
要访问嵌套属性,请使用
一种常见的模式是为泛型映射类型别名
type M map[string]interface{}
config := make(M)
yaml.Unmarshal(configFile, &config)
mysql := config["mysql"].(M)
host := mysql["host"].(string)
如果未提前定义类型,则需要从遇到的每个
接口{}
中选择适当的类型:
if db, ok := config["db"].(map[interface{}]interface{}); ok {
if mysql, ok := db["mysql"].(map[interface{}]interface{}); ok {
username := mysql["username"].(string)
// ...
}
}
请举例说明。您提供的代码正常工作,不会导致此错误。我更新了我的问题@jimbi,它有一个动态配置文件,可能涉及数组值“gopkg.in/yaml.v2”包的默认类型是
map[interface{}]interface{}
if db, ok := config["db"].(map[interface{}]interface{}); ok {
if mysql, ok := db["mysql"].(map[interface{}]interface{}); ok {
username := mysql["username"].(string)
// ...
}
}