查看变量类型
reflect.TypeOf(abc)
func main() {
var abc map[int]string
tttype := reflect.TypeOf(abc)
fmt.Println(tttype)
}
查看结构体字段说明
ttType.Fiel(num)
package main
import (
"fmt"
"reflect"
)
type TagType struct {
field1 bool "An important answer"
field2 string "The name of the thing"
field3 int "How much there are"
}
func refTag(tt TagType, ix int) {
ttType := reflect.TypeOf(tt)
ixField := ttType.Field(ix)
fmt.Printf("%v\n", ixField.Tag)
}
func main() {
tt := TagType{true, "Barak Obama", 1}
for i := 0; i < 3; i++ {
refTag(tt, i)
}
}
//
An important answer
The name of the thing
How much there are
通过反射修改结构体值
package main
import (
"fmt"
"reflect"
)
type T struct {
A int
B string
}
func main() {
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface())
}
s.Field(0).SetInt(77)
s.Field(1).SetString("hehe")
fmt.Println("t is now", t)
}
0: A int = 23
1: B string = skidoo
t is now {77 hehe}