GO: struct tag Examples
2017-12-28 18:37
399 查看
获取tag的内容是利用反射包来实现的,直接上 Example
Example01
Output01
Example02
Output02
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
相关文章推荐
- Go(5 [struct | tag | 方法 | 继承 ])
- Go struct tag深入理解
- golang <转>Go语言struct tag介绍
- 使用 Go 的 struct tag 来解析版本号字符串
- Go:Struct Tag
- go structTag
- go语言struct中的tag
- 8.笔记go语言——复杂类型struct,slice,map
- 谈一谈Go的结构体struct的使用方法
- Go - Struct
- Go语言中struct的匿名属性特征
- GO语言基础之struct
- php trait和go struct的匿名字段
- Go语言核心之美 3.4-Struct结构体
- Go语言学习四:struct类型
- Go语言struct类型介绍
- 18.4 Struct examples
- linux代码移植到windows下“error missing struct tag”
- 数据库 struct tag的问题
- Go语言笔记:struct结构遍历