go反射
一、基本用法
1.1、获取变量类型信息
var x float64 = 1.1
fmt.Println("type:", reflect.TypeOf(x))
// type: float64
1.2、获取变量具体值
var x float64 = 1.1
fmt.Println("type:", reflect.ValueOf(x))
// type: 1.1
1.3、获取具体类型
var x float64 = 1.1
v := reflect.ValueOf(x)
fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
// kind is float64: true
1.4、修改传入值
注意:只能使用*type类型的变量否则会panic
var x int = 3
v := reflect.ValueOf(&x)
e := v.Elem()
fmt.Println("e.CanSet:", e.CanSet())
e.SetInt(1)
fmt.Println("x", x)
// e.CanSet: true
// x: 1
二、对结构的反射操作
package main
import (
"fmt"
"reflect"
)
type T struct {
A int
B string
}
func main() {
t := T {1, "BBB"}
e := reflect.ValueOf(&t).Elem()
typeofT := e.Type()
for i := 0; i< e.NumField(); i++ {
f := e.Field(i)
fmt.Printf("%d: %s %s = %v\n",
i,
typeofT.Field(i).Name,
f.Type(),
f.Interface())
}
}
// 0: A int = 1
// 1: B string = BBB
博客主要介绍了Go反射的相关内容。包括基本用法,如获取变量类型信息、具体值、具体类型以及修改传入值,同时强调修改传入值时需使用*type类型变量,否则会panic。此外,还提及了对结构的反射操作。
4182

被折叠的 条评论
为什么被折叠?



