Golang Code Pieces

获取结构体tag

2019-06-22  本文已影响0人  yanjusong
package main

import (
    "fmt"
    "reflect"
)

type T struct {
    A int    `json:"aaa" test:"testaaa"`
    B string `json:"bbb" test:"testbbb"`
}

func main() {
    t := T{
        A: 123,
        B: "hello",
    }

    tt := reflect.TypeOf(t)
    for i := 0; i < tt.NumField(); i++ {
        field := tt.Field(i)
        if json, ok := field.Tag.Lookup("json"); ok {
            fmt.Println(json)
        }
        test := field.Tag.Get("test")
        fmt.Println(test)

        if none, ok := field.Tag.Lookup("none"); ok {
            fmt.Println(none)
        } else {
            fmt.Println("Lookup: doesn't exist \"none\" tag")
        }

        none := field.Tag.Get("none")
        if none == "" {
            fmt.Println("Get: doesn't exist \"none\" tag")
        }
    }
}

Output:

image.png
上一篇 下一篇

猜你喜欢

热点阅读