一、介绍

reflect包次要用来查看interface{}类型的类型type和值value
咱们能够用

reflect.TypeOf()  失去  reflect.Type 反射类型reflect.ValueOf() 失去  reflect.Value 反射值

二、reflect.Type

在这里咱们以struct举例:关上源码 src/reflect/type.go

type Type interface {    //通用的3个函数    //返回kind,根底类型,Struct,Bool,Int,Int8,Array,Chan,Func,Map...    Kind() Kind    //返回构造体名称    Name() string    //返回包门路    PkgPath() string     //struct相干的3个重要办法,能够看到如果不是struct的话,会报错    // Field returns a struct type's i'th field.    // It panics if the type's Kind is not Struct.    // It panics if i is not in the range [0, NumField()).    Field(i int) StructField    // FieldByName returns the struct field with the given name    // and a boolean indicating if the field was found.    FieldByName(name string) (StructField, bool)    // NumField returns a struct type's field count.    // It panics if the type's Kind is not Struct.    NumField() int}

本文次要截取了reflect.Type的6个办法以及StructField构造体

  1. 通用的办法 Kind(),Name(),PkgPath()
  2. struct相干办法 NumField(),FieldByName(),Field()
  3. StructField构造体,用来形容struct

咱们先看一个构造体

type Person struct {    Name string `json:"name"`    Age  int    `json:"age"`}

二、reflect.Value