zl程序教程

您现在的位置是:首页 >  后端

当前栏目

golang reflect反射:对基本数据类型、对struct结构体进行反射(获取值)代码示例

Golang反射代码 获取 进行 示例 基本 结构
2023-09-14 09:01:53 时间

代码

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)
}

// Student 对struct进行反射
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