Go Refletion 反射

2017-07-11  本文已影响0人  sirius_ztz

Type

我们可以通过Tyepof来获取变量的值,但要区分type和kind,前者表示真实类型(静态类型),后者表示基础结构(底层类型)

type X int 

func main(){
    var a X=100
    t:=reflect.TypeOf(a)

    fmt.Println(t.Name(),t.Kind())
}

输出:

X int

方法Elem返回指针、数组、切片、字典(值)或通道的类型

func main(){
    fmt.Println(reflect.TypeOf(map[string]int{}).Elem())
    fmt.Println(reflect.TypeOf([]int32{}).Elem())
}

输出:

int
int32

Value

《The way to Go》中的一段代码:
通过反射来遍历struct

package main
import (
    "fmt"
    "reflect"
)
type NotknownType struct {
    s1, s2, s3 string
}
var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
func main() {
    value := reflect.ValueOf(secret)
    for i := 0; i < value.NumField(); i++ {
        fmt.Printf("Field %d: %v\n", i, value.Field(i))
        //也可以将value的值输出出来,当必须是类型一致,如
        fmt.Println(value.Field(i).String())
    }
}
type inter int
    var x inter=45
    var y float64 = 3.4


    fmt.Println("type:", reflect.TypeOf(x)) //reflect.TypeOf includes an empty interface
    //When we call reflect.TypeOf(x), x is first stored in an empty interface, which is then passed as the argument;
    fmt.Println("value:", reflect.ValueOf(x))
    fmt.Println("type:", reflect.TypeOf(y))

    //Both reflect.Type and reflect.Value have lots of methods to let us examine and manipulate them
    v := reflect.ValueOf(y) //得到Valueof变量
    fmt.Println("type:", v.Type())
    fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
    fmt.Println("value:", v.Float())

    var z uint8 = 'x'
    h := reflect.ValueOf(z)
    fmt.Println("type:", h.Type())                            // uint8.
    fmt.Println("kind is uint8: ", h.Kind() == reflect.Uint8) // true.
    fmt.Println(h.Uint())          
上一篇 下一篇

猜你喜欢

热点阅读