获取Struce的Tag
package main
import (
"fmt"
"reflect"
)
type Foo struct {
FirstName string `tag_name:"tag 1"`
LastName string `tag_name:"tag 2"`
Age int `tag_name:"tag 3"`
}
func (f *Foo) reflect() {
val := reflect.ValueOf(f).Elem()
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
tag := typeField.Tag
fmt.Printf("Field Name: %s,t Field Value: %v,t Tag Value: %sn", typeField.Name, valueField.Interface(), tag.Get("tag_name"))
}
}
func main() {
f := &Foo{
FirstName: "Drew",
LastName: "Olson",
Age: 30,
}
f.reflect()
}
package main
import (
"fmt"
"reflect" // 这里引入reflect模块
)
type User struct {
Name string "user name" //这引号里面的就是tag
Passwd string "user passsword"
}
func main() {
user := &User{"chronos", "pass"}
s := reflect.TypeOf(user).Elem() //通过反射获取type定义
for i := 0; i < s.NumField(); i++ {
fmt.Println(s.Field(i).Tag) //将tag输出出来
}
}
// 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"))
}
近期评论