1.reflect代码示例
package main
import (
"fmt"
"reflect"
)
func RefectNum(arg interface{}) {
fmt.Println("type :", reflect.TypeOf(arg))
fmt.Println("value :", reflect.ValueOf(arg))
}
type Person struct {
ID int64
Name string
Age int64
}
func (this *Person) Call() {
fmt.Println("user is called ")
fmt.Printf("user is %v\n", this)
}
func DoFileAndMethod(input interface{}) {
// 获取input的type
inputType := reflect.TypeOf(input)
// fmt.Println("input type:", inputType.Name()) // Person
// 获取Input的value
inputValue := reflect.ValueOf(input)
// fmt.Println("input type:", inputValue) // {1 Allice 24}
// 通过type获取里面的字段
// 1.获取interface的reflect.Type,通过type得到NumField,进行遍历
// 2.得到每个filed,数据类型
// 3.通过每个field的interface{}获取到对应的value
for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
value := inputValue.Field(i).Interface()
fmt.Printf("%s:%v = %v\n", field.Name, field.Type, value)
}
}
func main() {
// var num float64 = 1.2345
// RefectNum(num)
user := Person{1, "Allice", 24}
DoFileAndMethod(user)
}
// 结果:
input type: Person
input type: {1 Allice 24}
ID:int64 = 1
Name:string = Allice
Age:int64 = 24
感觉兴趣的小伙伴可以加好友一起交流!!