golangの日記

Go言語を中心にプログラミングについてのブログ

Go言語(golang) reflectで構造体のタグ/アノテーションを取得する

golang.png


JSONやYAMLなどで使う構造体のタグ/アノテーションを取得する

type A struct {
   B string `これ`
}


package main

import (
    "fmt"
    "reflect"
)

// configの部分は好きにつける
type Server struct {
    Host string `config:"host"`
    Addr string `config:"addr"`
    Port int    `config:"port"`
}

func main() {
    s := Server{
        Host: "localhost",
        Addr: "127.0.0.1",
        Port: 8080,
    }

    t := reflect.TypeOf(s)
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        // Tag.Get("タグ名") でタグの内容を取れる
        fmt.Printf("Name: %s, Tag: %s\n",
            field.Name, field.Tag.Get("config"))
    }
    // // 実行結果
    // Name: Host, Tag: host
    // Name: Addr, Tag: addr
    // Name: Port, Tag: port
}