查看变量类型

reflect.TypeOf(abc)

  1. func main() {
  2. var abc map[int]string
  3. tttype := reflect.TypeOf(abc)
  4. fmt.Println(tttype)
  5. }

查看结构体字段说明

ttType.Fiel(num)

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type TagType struct {
  7. field1 bool "An important answer"
  8. field2 string "The name of the thing"
  9. field3 int "How much there are"
  10. }
  11. func refTag(tt TagType, ix int) {
  12. ttType := reflect.TypeOf(tt)
  13. ixField := ttType.Field(ix)
  14. fmt.Printf("%v\n", ixField.Tag)
  15. }
  16. func main() {
  17. tt := TagType{true, "Barak Obama", 1}
  18. for i := 0; i < 3; i++ {
  19. refTag(tt, i)
  20. }
  21. }
  22. //
  23. An important answer
  24. The name of the thing
  25. How much there are

通过反射修改结构体值

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type T struct {
  7. A int
  8. B string
  9. }
  10. func main() {
  11. t := T{23, "skidoo"}
  12. s := reflect.ValueOf(&t).Elem()
  13. typeOfT := s.Type()
  14. for i := 0; i < s.NumField(); i++ {
  15. f := s.Field(i)
  16. fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface())
  17. }
  18. s.Field(0).SetInt(77)
  19. s.Field(1).SetString("hehe")
  20. fmt.Println("t is now", t)
  21. }
  22. 0: A int = 23
  23. 1: B string = skidoo
  24. t is now {77 hehe}