GO 快速学会使用反射
1. 介绍
在反射的世界里,我们拥有了获取一个对象的类型,属性及方法的能力。
在 Go 反射的世界里,有两种类型非常重要,是整个反射的核心,在学习 reflect 包的使用时,先得学习下这两种类型:
- reflect.Type
- reflect.Value
2. 方法示例
2.1 通过反射获取对象的键(类型)和值
package main
import (
"fmt"
"reflect"
)
//
func reflectNum(arg interface{
}) {
fmt.Println("type:",reflect.TypeOf(arg))
fmt.Println("value : ",reflect.ValueOf(arg))
}
func main() {
reflectNum(1.1234)
}
type: float64
value : 1.1234
注意,Go 中所有对象都是键+值组成的,含有这种特性的对象都是可以用 Type + Value 进行抽象的,这就是万能对象
2.2 反射对象的类型和属性
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
func (this User) Call() {
fmt.Println("user is called ..")
fmt.Printf("#{this}\n")
}
func main() {
user := User{
1,"Aceld",18}
//传入 user 对象
DoFiledAndMethod(user)
}
//接收万能对象 用反射解析
func DoFiledAndMethod(input interface{
}) {