您的位置:首页 > 编程语言 > Go语言

GO: struct tag Examples

2017-12-28 18:37 399 查看
获取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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  golang