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,原文链接:https://www.f2er.com/go/190217.html