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.

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

报告相同问题?