GO学习——reflect(2)

Go 反射官网详解
http://golang.org/doc/articles/laws_of_reflection.html

demo

package main

import (
    "fmt"
    "reflect"
)


func main() {
    // GO reflect
    name := "jaspersong"
    // 得到类型的元数据,通过t我们能获取类型定义里面的所有元素
    t := reflect.TypeOf(name)

    // 得到实际的值,通过v我们获取存储在里面的值,还可以去改变值
    v := reflect.ValueOf(name)
    fmt.Println("name's TypeOf is ", t)
    fmt.Println("name's ValueOf is ", v)
    fmt.Println("type is ", v.Type())


    fmt.Println("--------------------")

    var x float64 = 3.4
    tt := reflect.TypeOf(x)
    vv := reflect.ValueOf(x)
    fmt.Println("xx's TypeOf is ", tt)
    fmt.Println("xx's ValueOf is ", vv)

    // TypeOf 和 Type值是一样的
    fmt.Println("type is ", vv.Type())

    // 种类: 该类型所属的种类,reflect包定义了Kind类型来表示各种类型。重命名一个类型并不会改变其种类
    fmt.Println("kind is float64 is ", vv.Kind() == reflect.Float64)
    fmt.Println("value is ", vv.Float())

    fmt.Println("--------------------")

    var y float64 = 3.4
    yt := reflect.TypeOf(y)
    fmt.Println("y's TypeOf is ", yt)
    // 转指针地址,可以进行值的修改
    // yv的值为y的指针地址
    yv := reflect.ValueOf(&y)
    fmt.Println("y's ValueOf is ", yv)

    // 这里的yv是一个指针类型的float64
    fmt.Println("yv's type is ", yv.Type())

    // 修改yv值,并不是设置yv这个指针的值
    // 所以通过Elem先获取到指针指向的值
    ye := yv.Elem()
    fmt.Println("yv's Elem is ", ye)
    // 修改值
    ye.SetFloat(7.1)
    fmt.Println("ye's vlue is ", ye)
}

运行结果:

name's TypeOf is  string
name's ValueOf is  jaspersong
type is  string
--------------------
xx's TypeOf is  float64
xx's ValueOf is  3.4
type is  float64
kind is float64 is  true
value is  3.4
--------------------
y's TypeOf is  float64
y's ValueOf is  0xc0420080e0
yv's type is  *float64
yv's Elem is  3.4
ye's vlue is  7.1