反射:可以在运行时动态获取变量的相关信息 Import (“reflect”) 两个函数: a. reflect.TypeOf,获取变量的类型,返回reflect.Type类型 b. reflect.ValueOf,获取变量的值,返回reflect.Value类型 c. reflect.Value.Kind,获取变量的类别,返回一个常量 d. reflect.Value.Interface(),转换成interface{}类型
reflect.Value.Kind()方法返回的常量: 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 UnsafePointer ) 获取变量的值: reflect.ValueOf(x).Float() reflect.ValueOf(x).Int() reflect.ValueOf(x).String() reflect.ValueOf(x).Bool() 通过反射的来改变变量的值: reflect.Value.SetXX相关方法,比如: reflect.Value.SetFloat(),设置浮点数 reflect.Value.SetInt(),设置整数 reflect.Value.SetString(),设置字符串
package main
import (
"reflect"
"fmt"
)
type Student struct {
Name string
Age int
Score float32
}
func test(b interface{}) {
t := reflect.TypeOf(b)
fmt.Println(t)
v := reflect.ValueOf(b)
k := v.Kind()
fmt.Println(k)
iv := v.Interface()
fmt.Println("iv:",iv)
stu, ok := iv.(Student)
if ok {
fmt.Printf("stu: %v %T\n", stu, stu)
}
}
func main() {
var a int = 200
test(a)
fmt.Println("<br/>")
var b Student = Student{
Name: "stu01",
Age: 18,
Score: 92,
}
test(b)
}
输出: int int iv: 200 <br/> main.Student struct iv: {stu01 18 92} stu: {stu01 18 92} main.Student
Process finished with exit code 0