func main() {
var x float64 = 3.4
//1.获取类型信息
fmt.Println("type:", reflect.TypeOf(x)) //type: float64
v := reflect.ValueOf(x)
fmt.Println("type:", v.Type()) //type: float64
fmt.Println("kind is float64:", v.Kind() == reflect.Float64) //kind is float64: true
fmt.Println("value:", v.Float()) //value: 3.4
fmt.Println("------------------------")
//2.获取值类型
fmt.Println("value:", v.CanSet()) //value: false 值不可以修改
p := reflect.ValueOf(&x) // 注意:得到X的地址
fmt.Println("type of p:", p.Type()) //type of p: *float64
fmt.Println("settability of p:", p.CanSet()) //settability of p: false
v = p.Elem()
fmt.Println("settability of v:", v.CanSet()) //settability of v: true
v.SetFloat(7.1)
fmt.Println(v.Interface()) //7.1
fmt.Println(x) //7.1
}
输出结果:
type: float64
type: float64
kind is float64: true
value: 3.4
------------------------
value: false
type of p: *float64
settability of p: false
settability of v: true
7.1
7.1
2.对结构的反射操作
type T struct {
A int
B string
}
func main() {
t := T{203, "mh203"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface())
}
}