Member-only story
Understanding Reflection in Go: Types and Kinds
Reflection in Go is supported by the reflect
package, which defines two essential types: Type
and Value
. In reflection, any value can be understood as composed of reflect.Type
and reflect.Value
. The reflect
package provides two functions, reflect.TypeOf
and reflect.ValueOf
, to obtain the Value
and Type
of any object. In a Go program, you can use the reflect.TypeOf()
function to get the type object (reflect.Type) of any value, and through this type object, you can access the type information of any value.
Compared to Type
, Kind
represents a broader category, similar to the relationship between home appliances (Kind) and television sets (Type). Alternatively, it's like the relationship between television sets (Kind) and 42-inch color television sets (Type). Type
is the type, while Kind
is the category. Type
and Kind
can be the same or different. Typically, the basic data types have the same Type
and Kind
, while custom data types have different ones. In reflection, you can obtain the kind through reflect.Type
or reflect.Value
, and the values and types obtained are the same.
Kinds represent the categories to which objects belong, and the reflect
package defines them as follows:
type Kind uint
const (
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…