golang-反射机制
2015-09-06 10:39
483 查看
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
,
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
,
相关文章推荐
- godaddy.com 注册域名 买卖域名
- [转]为什么GOF的23种设计模式里面没有MVC?
- mongo备份与恢复工具的对比与说明
- 外媒:Google Play将重返中国大陆
- leetcode: (94) Binary Tree Inorder Traversal
- Django:手把手带你入门
- Go基本语句
- 中国正沦为3D打印的配角?
- Going Graphical — The dialog Utility
- Godaddy域名因为whois信息虚假被暂时关闭
- Good Firewall(字典树 HDU4760)
- Good Firewall(字典树 HDU4760)
- leetcode: (144) Binary Tree Preorder Traversal
- 第五章 模版和Static Media
- Golang中的协程
- leetcode: (235) Lowest Common Ancestor of a Binary Search Tree
- django 1.8 官方文档翻译: 3-3-5 编写自定义存储系统
- leetcode: (100) Same Tree
- Django的TEMPLATES设置项(1.8新特性)
- 2015 Google hosts 持续更新【更新于:2015-09-01】