代码
package main
import (
"fmt"
"reflect"
)
func main() {
var num int=10
reflectTest01(num)
stu:=Student{
"tom",20}
reflectTest02(stu)
}
func reflectTest01(b interface{
}){
rType := reflect.TypeOf(b)
fmt.Println("rType=",rType)
rVal := reflect.ValueOf(b)
n2 := 2 + rVal.Int()
fmt.Println("n2=",n2)
fmt.Printf("rVal=%v\n rVal type=%T\n",rVal,rVal)
iV := rVal.Interface()
num2 := iV.(int)
fmt.Println("num2=",num2)
}
type Student struct {
Name string
Age int
}
func reflectTest02(b interface{
}){
rTyp := reflect.TypeOf(b)
fmt.Println("rTyp=",rTyp)
rVal := reflect.ValueOf(b)
iV := rVal.Interface()
fmt.Printf("iv=%v iv type=%T\n",iV,iV)
student,ok := iV.(Student)
if ok{
fmt.Printf("student.Name=%v\n",student.Name)
}
}
结果
rType= int
n2= 12
rVal=10
rVal type=reflect.Value
num2= 10
rTyp= main.Student
iv={tom 20} iv type=main.Student
student.Name=tom