23
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

go で yaml 等を「map[interface{}]interface{}」型で読み込んだ際の動的型の参照方法

前回の続きになるが、

goyamlを使うとyamlをmap[interface{}]interface{} な型で読み込める

config
mail_from: hoge@fuga.com
to: [hoge@fuga.com]
var:
  c: 2
  d: [3, 4]

このyamlを以下のコードで読み込むと

example.go
    m := make(map[interface{}]interface{})
    err = goyaml.Unmarshal([]byte(config), &m)
    if err != nil {
        panic(err)
    }
    //fmt.Printf("--- m:\n%# v\n\n", m)
    pretty.Printf("--- m:\n%# v\n\n", m)

以下のような形で読み込まれる

$ go run main.go
--- m:
map[interface {}]interface {}{
    "mail_from": "hoge@fuga.com",
    "to":        []interface {}{
        "hoge@fuga.com",
    },
    "var": map[interface {}]interface {}{
        "c": int(2),
        "d": []interface {}{
            int(3),
            int(4),
        },
    },
}

上記の場合toは、

fmt.Printf("--- m.to:\n%# v\n\n", m["to"])

でアクセスできるが、
var.c を読みたい場合は、

fmt.Printf("--- m.var.c:\n%# v\n\n", m["var"]["c"])

ではm["var"]の型がinterface{}のためにそのままでは読めない。

以下のように型アサーションを使ってアクセスすると読める

fmt.Printf("--- m.var.c:\n%# v\n\n", m["var"].(map[interface {}]interface {})["c"])

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
23
Help us understand the problem. What are the problem?