28
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-02-25

前回の続きになるが、

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"])

28
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?