golang之反射

反射这个概念绝大多数语言都有,比如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 }
The 0 th ordId types int valuing 456
The 1 th customerId types int valuing 56
The 2 th callback types func valuing 

首先,我们用 reflect.TypeOf(q)
reflect.ValueOf(q)
获取了结构体order的类型和值,然后我们再从循环里对它的成员进行一个遍历,并将所有成员的名称和类型打印了出来。这样,一个结构体的所有信息就都暴露在我们面前。