1、反射:可以在运行时动态获取变量的相关信息

Import(“reflect”)

两个函数:

reflect.TypeOf()//获取变量的类型,返回reflect.Type类型
reflect.ValueOf()//获取变量的值,返回reflect.Value类型
reflect.Value.Kind()//获取变量的类别,返回一个常量
reflect.Value.Interface()//转换成interface{}类型

Golang之反射(重点!!)可逆状态

示例用法

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Name  string
    Age   int
    Score float32
}

func test(b interface{}) {
    t := reflect.TypeOf(b)
    fmt.Println(t)

    v := reflect.ValueOf(b)
    k := v.Kind()
    fmt.Println(k)

    iv := v.Interface()
    stu, ok := iv.(Student)
    if ok {
        fmt.Printf("%v %T\n", stu, stu)
    }
}
func testInt(b interface{}) {
    val := reflect.ValueOf(b)
    c := val.Int()
    fmt.Printf("get value interface{} %d\n", c)
}

func main() {
    var a Student = Student{
        Name:  "stu01",
        Age:   18,
        Score: 92,
    }
    test(a)
    testInt(1234)
}
反射用法

相关文章: