go言語の学習:構造体よりタグ情報を取得
構造体にあるjsonなどのタグより取得
package main import ( "fmt" "reflect" ) type Sample struct { no int `sampletag:"aaaaa"` name string `sampletag:"bbbbb"` age int `sampletag:"ccccc"` } func main() { fmt.Println("start") // Sample1インターフェースを定義 var sample1 Sample // 型の取得 t := reflect.TypeOf(sample1) // タグの情報を取得 for i:=0;i<t.NumField();i++ { item := t.Field(i) fmt.Printf("index: %2d, name:%10s, type:%10s, tag:%10s\n", i, item.Name, item.Type.Name(), item.Tag.Get("sampletag")) } fmt.Println("end") }
↓
start index: 0, name: no, type: int, tag: aaaaa index: 1, name: name, type: string, tag: bbbbb index: 2, name: age, type: int, tag: ccccc end
DBのORMやjsonのエンコード、デコードなどで使用されている
タグ情報を設定することで構造体の項目のバリデーションなどにも併用できる感じ…