分享
golang之反射
aside section ._1OhGeD · · 1262 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
反射这个概念绝大多数语言都有,比如Java,PHP之类,golang自然也不例外,反射其实程序能够自描述和自控制的一类机制。
比如,通过PHP的反射,你可以知道一个类有什么成员,有什么方法。而golang,也能够通过官方自带的reflect包来了解各种变量类型及其信息。
下面我们通过一个例子查看反射的基本用法。
话不多说,直接贴代码:
package main
import (
"fmt"
"reflect"
)
type Order struct {
ordId int
customerId int
callback func()
}
func reflectInfo(q interface{}) {
t := reflect.TypeOf(q)
v := reflect.ValueOf(q)
fmt.Println("Type ", t)
fmt.Println("Value ", v)
for i := 0; i < v.NumField(); i = i + 1 {
fv := v.Field(i)
ft := t.Field(i)
switch fv.Kind() {
case reflect.String:
fmt.Printf("The %d th %s types %s valuing %s\n", i, ft.Name, "string", fv.String())
case reflect.Int:
fmt.Printf("The %d th %s types %s valuing %d\n", i, ft.Name, "int", fv.Int())
case reflect.Func:
fmt.Printf("The %d th %s types %s valuing %v\n", i, ft.Name, "func", fv.String())
}
}
}
func main() {
o := Order{
ordId: 456,
customerId: 56,
}
reflectInfo(o)
}
以上程序的输出:
Type main.order
Value {456 56 <nil>}
The 0 th ordId types int valuing 456
The 1 th customerId types int valuing 56
The 2 th callback types func valuing <func() Value>
首先,我们用reflect.TypeOf(q)和reflect.ValueOf(q)获取了结构体order的类型和值,然后我们再从循环里对它的成员进行一个遍历,并将所有成员的名称和类型打印了出来。这样,一个结构体的所有信息就都暴露在我们面前。
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1262 次点击
上一篇:golang拼接字符串性能测试
下一篇:ETH-Ubuntu下安装
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
反射这个概念绝大多数语言都有,比如Java,PHP之类,golang自然也不例外,反射其实程序能够自描述和自控制的一类机制。
比如,通过PHP的反射,你可以知道一个类有什么成员,有什么方法。而golang,也能够通过官方自带的reflect包来了解各种变量类型及其信息。
下面我们通过一个例子查看反射的基本用法。
话不多说,直接贴代码:
package main
import (
"fmt"
"reflect"
)
type Order struct {
ordId int
customerId int
callback func()
}
func reflectInfo(q interface{}) {
t := reflect.TypeOf(q)
v := reflect.ValueOf(q)
fmt.Println("Type ", t)
fmt.Println("Value ", v)
for i := 0; i < v.NumField(); i = i + 1 {
fv := v.Field(i)
ft := t.Field(i)
switch fv.Kind() {
case reflect.String:
fmt.Printf("The %d th %s types %s valuing %s\n", i, ft.Name, "string", fv.String())
case reflect.Int:
fmt.Printf("The %d th %s types %s valuing %d\n", i, ft.Name, "int", fv.Int())
case reflect.Func:
fmt.Printf("The %d th %s types %s valuing %v\n", i, ft.Name, "func", fv.String())
}
}
}
func main() {
o := Order{
ordId: 456,
customerId: 56,
}
reflectInfo(o)
}
以上程序的输出:
Type main.order
Value {456 56 <nil>}
The 0 th ordId types int valuing 456
The 1 th customerId types int valuing 56
The 2 th callback types func valuing <func() Value>
首先,我们用reflect.TypeOf(q)和reflect.ValueOf(q)获取了结构体order的类型和值,然后我们再从循环里对它的成员进行一个遍历,并将所有成员的名称和类型打印了出来。这样,一个结构体的所有信息就都暴露在我们面前。