golang-反射机制
发布时间:2020-12-16 18:39:31  所属栏目:大数据  来源:网络整理 
            导读:1,写数据库dao层的时候用到了反射机制。在反射的时候要注意你的对象时指针还是结构体这样区别也很大。以下接受几种常用的放射方法 reflect.type of package mainimport ("fmt""reflect")type hehe struct {NameFile string "PrimaryKey"age int}func main()
                
                
                
            | 1,写数据库dao层的时候用到了反射机制。在反射的时候要注意你的对象时指针还是结构体这样区别也很大。以下接受几种常用的放射方法 reflect.type of package main
import (
	"fmt"
	"reflect"
)
type hehe struct {
	NameFile string "PrimaryKey"
	age      int
}
func main() {
	hehe := &hehe{"ssssssssssss",33}
	yingShe(hehe)
}
func yingShe(obj interface{}) {
	hehe := &hehe{"ssssssssssss",22}
	for i := 0; i < reflect.TypeOf(obj).Elem().NumField(); i++ {
		f := reflect.TypeOf(obj).Elem().Field(i)
		fmt.Print(f.Name," : ")
		switch reflect.ValueOf(hehe).Elem().FieldByName(f.Name).Kind() {
		case reflect.Int:
			val := reflect.ValueOf(hehe).Elem().FieldByName(f.Name).Int()
			fmt.Println(val)
		default:
			val := reflect.ValueOf(hehe).Elem().FieldByName(f.Name)
			fmt.Print(val)
		}
		fmt.Println(",",reflect.TypeOf(hehe).Elem().Field(i).Tag)
	}
}
运行结果NameFile : ssssssssssss,PrimaryKey age : 22, (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
