23 September 2017

Table of Contents

type

type Human struct {
      name   string
      age    int
      weight int
}
human := Human{"Mark", 25, 120}

reflectType := reflect.TypeOf(human)
fmt.Printf("%v\n", reflectType.Name())        // Human
fmt.Printf("%v\n", reflectType.String())      // main.Human
fmt.Printf("%v\n", reflectType.Kind())        // struct
fmt.Printf("%v\n", reflectType.NumField())    // 3
fmt.Printf("%v\n", reflectType.Field(0))      //
fmt.Printf("%v\n", reflectType.Field(0).Name) // name
fmt.Printf("%v\n", reflectType.Field(0).Type) // string

Kind

Invalid Kind = iota
Bool
Int
Int8
Int16
Int32
Int64
Uint
Uint8
Uint16
Uint32
Uint64
Uintptr
Float32
Float64
Complex64
Complex128
Array
Chan
Func
Interface
Map
Ptr
Slice
String
Struct
UnsafePointer

value

human := Human{"Mark", 25, 120}

reflectValue := reflect.ValueOf(human)
fmt.Printf("%v", reflectValue.Field(0).String()) // Mark
fmt.Printf("%v", reflectValue.Field(0).String()) // Mark
fmt.Printf("%v", reflectValue.Interface())       // {Mark 25 120}

reflectValue.Field(0) 也是一个 value

// 错误
var x float64 = 3.4
ref := reflect.ValueOf(x)
ref.SetFloat(1.0)
fmt.Println("value:", ref.Float())


// 设置值的时候必须是指针
var x float64 = 3.4
refp := reflect.ValueOf(&x)
ref := refp.Elem()
ref.SetFloat(1.0)
fmt.Println("value: ", ref.Float())

type value

human := Human{"name", 12, 110}

reflectType := reflect.TypeOf(human)
reflectValue := reflect.ValueOf(human)
for i := 0; i < reflectType.NumField(); i++ {
      field := reflectType.Field(i)
      switch field.Type.Kind() {
      case reflect.Int:
              fmt.Printf("%v\n", reflectValue.Field(i).Int())
      case reflect.String:
              fmt.Printf("%v\n", reflectValue.Field(i).String())
      case reflect.Float64:
              fmt.Printf("%v\n", reflectValue.Field(i).Float())
      }
}