package main
import (
"fmt"
"reflect"
"unsafe"
)
type ss struct {
a struct {
int
string
}
int
string
bool
float64
}
func (s ss) Method1(i int) string { return "结构体方法1" }
func (s *ss) Method2(i int) string { return "结构体方法2" }
var (
intValue = int(0)
int8Value = int8(8)
int16Value = int16(16)
int32Value = int32(32)
int64Value = int64(64)
uIntValue = uint(0)
uInt8Value = uint8(8)
uInt16Value = uint16(16)
uInt32Value = uint32(32)
uInt64Value = uint64(64)
byteValue = byte(0)
runeValue = rune(0)
uintptrValue = uintptr(0)
boolValue = false
stringValue = "stringValue"
float32Value = float32(32)
float64Value = float64(64)
complex64Value = complex64(64)
complex128Value = complex128(128)
arrayValue = [5]string{}
sliceValue = []byte{0, 0, 0, 0, 0}
mapValue = map[string]int{}
chanValue = make(chan int, 2)
structValue = ss{
struct {
int
string
}{10, "子结构体"},
20,
"结构体",
false,
64.0,
}
func1Value = func(i int) string {
return fmt.Sprintf("固定参数:%v", i)
}
func2Value = func(i ...int) string {
return fmt.Sprintf("动态参数:%v", i)
}
unsafePointer = unsafe.Pointer(&structValue)
reflectType = reflect.TypeOf(0)
reflectValue = reflect.ValueOf(0)
reflectArrayValue = reflect.ValueOf([]int{1, 2, 3})
interfaceType = reflect.TypeOf(new(interface{})).Elem()
)
var simpleTypes = []interface{}{
intValue, &intValue,
int8Value, &int8Value,
int16Value, &int16Value,
int32Value, &int32Value,
int64Value, &int64Value,
uIntValue, &uIntValue,
uInt8Value, &uInt8Value,
uInt16Value, &uInt16Value,
uInt32Value, &uInt32Value,
uInt64Value, &uInt64Value,
byteValue, &byteValue,
runeValue, &runeValue,
uintptrValue, &uintptrValue,
boolValue, &boolValue,
stringValue, &stringValue,
float32Value, &float32Value,
float64Value, &float64Value,
complex64Value, &complex64Value,
complex128Value, &complex128Value,
}
var complexTypes = []interface{}{
arrayValue, &arrayValue,
sliceValue, &sliceValue,
mapValue, &mapValue,
chanValue, &chanValue,
structValue, &structValue,
func1Value, &func1Value,
func2Value, &func2Value,
structValue.Method1, structValue.Method2,
unsafePointer, &unsafePointer,
reflectType, &reflectType,
reflectValue, &reflectValue,
interfaceType, &interfaceType,
}
var unsafeP unsafe.Pointer
var nilInterfece interface{}
func main() {
for i := 0; i < len(simpleTypes); i++ {
PrintInfo(simpleTypes[i])
}
for i := 0; i < len(complexTypes); i++ {
PrintInfo(complexTypes[i])
}
PrintInfo(&unsafeP)
PrintInfo(nilInterfece)
}
func PrintInfo(i interface{}) {
if i == nil {
fmt.Println("--------------------")
fmt.Printf("无效接口值:%v\n", i)
fmt.Println("--------------------")
return
}
v := reflect.ValueOf(i)
PrintValue(v)
}
func PrintValue(v reflect.Value) {
fmt.Println("--------------------")
fmt.Println("String :", v.String())
fmt.Println("Type :", v.Type())
fmt.Println("Kind :", v.Kind())
fmt.Println("CanAddr :", v.CanAddr())
fmt.Println("CanSet :", v.CanSet())
if v.CanAddr() {
fmt.Println("Addr :", v.Addr())
fmt.Println("UnsafeAddr :", v.UnsafeAddr())
}
fmt.Println("CanInterface :", v.CanInterface())
if v.CanInterface() {
fmt.Println("Interface :", v.Interface())
}
fmt.Println("NumMethod :", v.NumMethod())
if v.NumMethod() > 0 {
i := 0
for ; i < v.NumMethod()-1; i++ {
fmt.Printf(" ┣ %v\n", v.Method(i).String())
}
fmt.Printf(" ┗ %v\n", v.Method(i).String())
fmt.Println("MethodByName :", v.MethodByName("String").String())
}
switch v.Kind() {
case reflect.Slice, reflect.Map, reflect.Chan, reflect.Func,
reflect.Ptr, reflect.UnsafePointer:
fmt.Println("Pointer :", v.Pointer())
}
switch v.Kind() {
case reflect.Ptr:
fmt.Println("=== 指针 ===")
if !v.IsNil() {
v = v.Elem()
fmt.Printf("转换到指针所指对象 : %v\n", v.Type())
PrintValue(v)
return
}
case reflect.UnsafePointer:
fmt.Println("=== 自由指针 ===")
if v.Pointer() == 0 {
v.SetPointer(unsafePointer)
fmt.Println("重新指向新对象 :", v.Pointer())
}
s := (*ss)(v.Interface().(unsafe.Pointer))
v = reflect.ValueOf(s)
if !v.IsNil() {
v = v.Elem()
fmt.Printf("转换到指针所指对象 : %v\n", v.Type())
PrintValue(v)
return
}
case reflect.Interface:
fmt.Println("=== 接口 ===")
fmt.Println("InterfaceData :", v.InterfaceData())
v = v.Elem()
fmt.Printf("转换到接口所含对象 : %v\n", v.Type())
PrintValue(v)
return
}
if reflect.Int <= v.Kind() && v.Kind() <= reflect.Int64 {
fmt.Println("=== 有符号整型 ===")
fmt.Println("Int :", v.Int())
if v.CanSet() {
v.SetInt(10)
fmt.Println("Int :", v.Int())
v.Set(reflect.ValueOf(20).Convert(v.Type()))
}
fmt.Println("Int :", v.Int())
fmt.Println("OverflowInt :", v.OverflowInt(10))
}
if reflect.Uint <= v.Kind() && v.Kind() <= reflect.Uint64 {
fmt.Println("=== 无符号整型 ===")
fmt.Println("Uint :", v.Uint())
if v.CanSet() {
v.SetUint(10)
fmt.Println("Uint :", v.Uint())
v.Set(reflect.ValueOf(20).Convert(v.Type()))
}
fmt.Println("Uint :", v.Uint())
fmt.Println("OverflowUint :", v.OverflowUint(10))
}
switch v.Kind() {
case reflect.Float32, reflect.Float64:
fmt.Println("=== 浮点数 ===")
fmt.Println("Float :", v.Float())
if v.CanSet() {
v.SetFloat(10)
fmt.Println("Float :", v.Float())
v.Set(reflect.ValueOf(20).Convert(v.Type()))
}
fmt.Println("Float :", v.Float())
fmt.Println("OverflowFloat :", v.OverflowFloat(10))
case reflect.Complex64, reflect.Complex128:
fmt.Println("=== 复数 ===")
fmt.Println("Complex :", v.Complex())
if v.CanSet() {
v.SetComplex(10)
fmt.Println("Complex :", v.Complex())
v.Set(reflect.ValueOf(20 + 20i).Convert(v.Type()))
}
fmt.Println("Complex :", v.Complex())
fmt.Println("OverflowComplex :", v.OverflowComplex(10))
case reflect.Bool:
fmt.Println("=== 布尔型 ===")
fmt.Println("Bool :", v.Bool())
if v.CanSet() {
v.SetBool(true)
fmt.Println("Bool :", v.Bool())
v.Set(reflect.ValueOf(false))
}
fmt.Println("Bool :", v.Bool())
case reflect.String:
fmt.Println("=== 字符串 ===")
fmt.Println("String :", v.String())
if v.CanSet() {
v.SetString("abc")
fmt.Println("String :", v.String())
v.Set(reflect.ValueOf("def"))
}
fmt.Println("String :", v.String())
case reflect.Slice:
fmt.Println("=== 切片型 ===")
fmt.Println("Len :", v.Len())
fmt.Println("Cap :", v.Cap())
if v.CanSet() {
v.SetLen(4)
v.SetCap(4)
fmt.Println("SetLen, SetCap :", v.Len(), v.Cap())
if v.Type().Elem().Kind() == reflect.Uint8 {
v.SetBytes([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0})
}
fmt.Println("SetByte :", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0})
}
if v.Type().Elem().Kind() == reflect.Uint8 {
fmt.Println("Bytes :", v.Bytes())
}
if v.Len() > 0 {
for i := 0; i < v.Len(); i++ {
fmt.Println("Index :", v.Index(i))
}
}
s1 := v.Slice(1, 2)
fmt.Println("Slice :", s1)
fmt.Println("Len :", s1.Len())
fmt.Println("Cap :", s1.Cap())
s2 := v.Slice3(1, 2, 4)
fmt.Println("Slice :", s2)
fmt.Println("Len :", s2.Len())
fmt.Println("Cap :", s2.Cap())
case reflect.Map:
fmt.Println("=== 映射型 ===")
v.SetMapIndex(reflect.ValueOf("a"), reflect.ValueOf(1))
v.SetMapIndex(reflect.ValueOf("b"), reflect.ValueOf(2))
v.SetMapIndex(reflect.ValueOf("c"), reflect.ValueOf(3))
fmt.Println("MapKeys :", v.MapKeys())
for _, idx := range v.MapKeys() {
fmt.Println("MapIndex :", v.MapIndex(idx))
}
case reflect.Struct:
fmt.Println("=== 结构体 ===")
fmt.Println("NumField :", v.NumField())
if v.NumField() > 0 {
var i, j int
for i = 0; i < v.NumField()-1; i++ {
field := v.Field(i)
fmt.Printf(" ├ %-8v %v\n", field.Type(), field.String())
if field.Kind() == reflect.Struct && field.NumField() > 0 {
for j = 0; j < field.NumField()-1; j++ {
subfield := v.FieldByIndex([]int{i, j})
fmt.Printf(" │ ├ %-8v %v\n", subfield.Type(), subfield.String())
}
subfield := v.FieldByIndex([]int{i, j})
fmt.Printf(" │ └ %-8v %v\n", subfield.Type(), subfield.String())
}
}
field := v.Field(i)
fmt.Printf(" └ %-8v %v\n", field.Type(), field.String())
if v := v.FieldByName("ptr"); v.IsValid() {
fmt.Println("FieldByName(ptr) :", v.Type().Name())
}
v := v.FieldByNameFunc(func(s string) bool { return len(s) > 3 })
if v.IsValid() {
fmt.Println("FieldByNameFunc :", v.Type().Name())
}
}
case reflect.Chan:
fmt.Println("=== 通道型 ===")
v.Send(reflectValue)
fmt.Println("TrySend :", v.TrySend(reflectValue))
if x, ok := v.Recv(); ok {
fmt.Println("Recv :", x)
}
if x, ok := v.TryRecv(); ok {
fmt.Println("TryRecv :", x)
}
case reflect.Func:
fmt.Println("=== 函数型 ===")
if v.Type().IsVariadic() {
fmt.Println("CallSlice :", v.CallSlice([]reflect.Value{reflectArrayValue}))
} else {
fmt.Println("Call :", v.Call([]reflect.Value{reflectValue}))
}
}
}