GO: struct tag Examples

獲取tag的內容是利用反射包來實現的,直接上 Example
Example01

package main

import (
    "fmt"
    "reflect"
)

type People struct {
    Name string "name" //引號裏面的就是tag
    Age int "age"
}

type S struct {
     F string `species:"gopher" color:"blue"`
}

func main() {
    people1 := &People{"Water", 28}
    s1 := reflect.TypeOf(people1)
    FieldTag(s1)

    people2 := S{"Water"}
    s2 := reflect.TypeOf(people2)
    FieldTag(s2)
}

func FieldTag(t reflect.Type) bool {
    if t.Kind() == reflect.Ptr {
        t = t.Elem()
    }

    if t.Kind() != reflect.Struct {
        return false
    }
    n := t.NumField()
    for i := 0; i < n; i++ {
        fmt.Println(t.Field(i).Tag)
    }
    return true
}

Output01

name
age
species:"gopher" color:"blue"

Example02

//Golang.org中reflect的示例代碼
package main

import (
    "fmt"
    "reflect"
)

func main() {
    type S struct {
        F string `species:"gopher" color:"blue"`
    }

    s := S{}
    st := reflect.TypeOf(s)
    field := st.Field(0)
    fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}

Output02

blue gopher
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章