今天研究了一下如何获取反射得到的结构体信息,有一个注意点。

获取结构体内部的字段名和字段值需要用到2个方法。

t := reflect.TypeOf(q)
v := reflect.ValueOf(q)

字段名 t.Field(i).Name   字段值 v.Field(i)

请参见下面代码:

package reflect

import (
    "fmt"
    "reflect"
)

func MyTest() {

    e := employee2{
        name:    "Naveen",
        id:      565,
        address: "Coimbatore",
        salary:  90000,
        country: "India",
    }
    DisplayStructInfo(e)

}

func DisplayStructInfo(q interface{}) {
    fmt.Println("显示结构体信息:")
    fmt.Println("结构体定义的类型 ", reflect.TypeOf(q))
    fmt.Println("结构体内容 ", reflect.ValueOf(q))
    fmt.Println("类型 ", reflect.TypeOf(q).Kind())

    fmt.Println("显示结构体字段的信息:")
    if reflect.ValueOf(q).Kind() == reflect.Struct {
        t := reflect.TypeOf(q)
        v := reflect.ValueOf(q)
        for i := 0; i < v.NumField(); i++ {
            fmt.Println("字段名称: ", t.Field(i).Name, "     字段值: ", v.Field(i), "     字段类型: ", v.Field(i).Kind())
        }
    }
}

type employee2 struct {
    name    string
    id      int
    address string
    salary  int
    country string
}

测试结果:

转载请注明出处: http://bluesd7.com/蓝影闪电的随笔/ContentId/157/Go-Golang-反射获取结构体和字段类型

 
标签: Go, Golang 分类: Go, 后端开发, 原创

评论数量 (2)

留下一个评论

剩余2000个字符。 一共限制在2000个字符内.
发送评论

搜索

关于我

姓名:余钊

英文名:Joshua

现居:武汉

Email: yuzhao_blue@163.com

关注:架构, 全栈, SQL, 高性能, 高并发

日历