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.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格