1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package main
import ( "fmt" "reflect" )
type resume struct { Name string `info:"name" doc:"名字"` Sex string `info:"sex"` }
func findTag(str interface{}) { var t reflect.Type = reflect.TypeOf(str).Elem() var v reflect.Value = reflect.ValueOf(str).Elem() for i := 0; i < t.NumField(); i++ { var fieldT reflect.StructField = t.Field(i) fmt.Println("fieldT: ", fieldT) var fieldV reflect.Value = v.Field(i) fmt.Println("fieldV: ", fieldV) fmt.Println("field Name: ", fieldT.Name) fmt.Println("field Type: ", fieldT.Type) fmt.Println("field Tag: ", fieldT.Tag) fmt.Println("field Interface: ", fieldV.Interface()) tagInfo := fieldT.Tag.Get("info") tagDoc := fieldT.Tag.Get("doc") fmt.Println("info: ", tagInfo, " doc: ", tagDoc) fmt.Println("----------------------------------------") } }
func main() { var a = 100 t1 := reflect.TypeOf(&a).Elem() fmt.Println("===============================") fmt.Println("Name: ", t1.Name()) fmt.Println("Kind: ", t1.Kind()) fmt.Println("t1: ", t1) fmt.Println("typeof t1: ", reflect.TypeOf(t1)) fmt.Println("===============================") t2 := reflect.TypeOf(&a) fmt.Println("Name: ", t2.Name()) fmt.Println("Kind: ", t2.Kind()) fmt.Println("t2: ", t2) fmt.Println("typeof t2: ", reflect.TypeOf(t2)) fmt.Println("==============================")
var re resume = resume{"张三", "男"} typeRe1 := reflect.TypeOf(re) fmt.Println("===============================") fmt.Println("Name: ", typeRe1.Name()) fmt.Println("Kind: ", typeRe1.Kind()) fmt.Println("typeRe1: ", typeRe1) fmt.Println("typeof typeRe1: ", reflect.TypeOf(typeRe1)) fmt.Println("===============================") typeRe2 := reflect.TypeOf(&re) fmt.Println("Name: ", typeRe2.Name()) fmt.Println("Kind: ", typeRe2.Kind()) fmt.Println("typeRe2: ", typeRe2) fmt.Println("typeof typeRe2: ", reflect.TypeOf(typeRe2)) fmt.Println("==============================") findTag(&re)
v1 := reflect.ValueOf(&re).Elem() v1.Set(reflect.Zero(v1.Type())) fmt.Println(v1) }
|