简体   繁体   English

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

[英]how to get struct field type in 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", n, f.Kind(), t)
    }
}

func main() {

    var u User
    ListFields(&u)
}

go run main.go 去运行main.go

Name: Id Kind: int64 Type: int64 名称:Id类型:int64类型:int64

Name: Name Kind: string Type: string 名称:名称类型:字符串类型:字符串

Name: Role Kind: int Type: main.Role <--- how to get int type ? 名称:角色类型:int类型:main.Role <---如何获取int类型?

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). 在Go Kind()返回基本类型(这是您要的内容),而Type()返回直接类型(已定义为自定义类型的内容)。 You'll never get the basic type from Type() for any custom types you've defined. 对于定义的任何自定义类型,您永远都不会从Type()获得基本类型。 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. 我对您的示例进行了一些修改,以帮助您理解Kind()总是返回实际的基本类型(或类型的种类,请参见https://golang.org/pkg/reflect/#Kind ),尽管有许多嵌套的自定义类型。

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", n, f.Kind(), t)
    }
}

func main() {

    var u User
    ListFields(&u)
}

https://goplay.space/#-eTlN4dGzj_k https://goplay.space/#-eTlN4dGzj_k

In other words both Kind and Type are types. 换句话说,Kind和Type都是类型。 They match for basic types (int64, string, etc.) and differ for custom types. 它们与基本类型(int64,字符串等)匹配,而与自定义类型不同。 There is no reason to substitute the Type value with Kind. 没有理由用Kind代替Type值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM