Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

前回の続きになるが、

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 do not you register as a user and use Qiita more conveniently?
  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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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