获取类型和值

  • TypeOf
  • ValueOf
  • pair
  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. var num int =10
  8. fmt.Println("type:",reflect.TypeOf(num))
  9. fmt.Println("value:",reflect.ValueOf(num))
  10. }
  1. type: int
  2. value: 10

获取字段和方法

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type User struct {
  7. Name string
  8. Age int
  9. }
  10. func (this User)Invoke() {
  11. fmt.Println("user method called")
  12. }
  13. func main() {
  14. var num int =10
  15. // 获取基础类型
  16. fmt.Println("type:",reflect.TypeOf(num))
  17. fmt.Println("value:",reflect.ValueOf(num))
  18. user :=User{
  19. Name: "Alice",
  20. Age: 19,
  21. }
  22. inputType := reflect.TypeOf(user)
  23. inputValue := reflect.ValueOf(user)
  24. // 遍历字段
  25. for i:=0;i<inputType.NumField();i++ {
  26. field := inputType.Field(i)
  27. fmt.Println("field:",field.Name,"value:",inputValue.Field(i).Interface())
  28. }
  29. // 遍历方法
  30. for i:=0;i<inputType.NumMethod();i++ {
  31. method := inputType.Method(i)
  32. fmt.Println("methodName:",method.Name)
  33. }
  34. }
  1. type: int
  2. value: 10
  3. field: Name value: Alice
  4. field: Age value: 19
  5. methodName: Invoke