获取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