duanbi2003 2018-04-07 03:41
浏览 121
已采纳

如何在golang中获取结构字段类型?

type Role int

type User struct {
    Id int64
    Name string
    Role Role
}

func ListFields(a interface{}) {
    v := reflect.ValueOf(a).Elem()
    for j := 0; j < v.NumField(); j++ {
        f := v.Field(j)
        n := v.Type().Field(j).Name
        t := f.Type().String()
        fmt.Printf("Name: %s  Kind: %s  Type: %s
", n, f.Kind(), t)
    }
}

func main() {

    var u User
    ListFields(&u)
}

go run main.go

Name: Id Kind: int64 Type: int64

Name: Name Kind: string Type: string

Name: Role Kind: int Type: main.Role <--- how to get int type ?

  • 写回答

1条回答 默认 最新

  • dongseshu0698 2018-04-07 05:59
    关注

    In Go Kind() returns the basic types (this is what you're asking for) and Type() returns the direct types (what you've defined as custom types). You'll never get the basic type from Type() for any custom types you've defined. I've modified your example a bit to help you understand that Kind() always returns the actual basic type (or kind of type, see https://golang.org/pkg/reflect/#Kind), despite many nested custom types.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type Role int
    type Role2 Role
    type Role3 Role2
    
    type User struct {
        Id   int64
        Name string
        Role Role3
    }
    
    func ListFields(a interface{}) {
        v := reflect.ValueOf(a).Elem()
        for j := 0; j < v.NumField(); j++ {
            f := v.Field(j)
            n := v.Type().Field(j).Name
            t := f.Type().String()
            fmt.Printf("Name: %s  Basic Type or Kind: %s  Direct or Custom Type: %s
    ", n, f.Kind(), t)
        }
    }
    
    func main() {
    
        var u User
        ListFields(&u)
    }
    

    https://goplay.space/#-eTlN4dGzj_k

    In other words both Kind and Type are types. They match for basic types (int64, string, etc.) and differ for custom types. There is no reason to substitute the Type value with Kind.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我下载图形界面重启完就变成这样了,打字也打不了,动也动不了,该怎么解决(操作系统-centos)
  • ¥15 VBA中在窗体中遍历所有checkbox控件,提取出被选中的checkbox的caption值
  • ¥15 在Ubuntu上有什么命令,或者是系统文件能告诉我链接nvme ssd的pcie槽位是不是支持热插拔功能?
  • ¥15 ansys license许可证问题
  • ¥20 QQ号和密码都能正常登录微信 QQ号和密码登录微信显示密码错误
  • ¥15 qiankun主应用注册子应用提示跨域
  • ¥15 单片机RTOS Kernel与应用分离开发,Kernel如何调起应用?
  • ¥15 快手小店商家版APP怎么第三方APP跳转到指定用户聊天界面
  • ¥15 为什么AVL fire软件仿真时的步长改变了,仿真结果也会改变
  • ¥100 如何帮我写一个java小游戏