查看变量类型
reflect.TypeOf(abc)
func main() {var abc map[int]stringtttype := reflect.TypeOf(abc)fmt.Println(tttype)}
查看结构体字段说明
ttType.Fiel(num)
package mainimport ("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 answerThe name of the thingHow much there are
通过反射修改结构体值
package mainimport ("fmt""reflect")type T struct {A intB 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 = 231: B string = skidoot is now {77 hehe}
