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

标签 go

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)
}

去运行main.go

姓名:Id 种类:int64 类型:int64

名称:名称种类:字符串类型:字符串

名称:Role 种类:int 类型:main.Role <--- 如何获取 int 类型?

最佳答案

在 Go 中,Kind() 返回基本类型(这是您要求的),Type() 返回直接类型(您定义的作为自定义类型)。对于您定义的任何自定义类型,您永远不会从 Type() 获得基本类型。我对您的示例做了一些修改,以帮助您理解 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

换句话说,Kind 和 Type 都是类型。它们与基本类型(int64、字符串等)匹配,而与自定义类型不同。没有理由用 Kind 替换 Type 值。

关于go - 如何在golang中获取结构字段类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49703588/

相关文章:

Golang 的 "internal error: duplicate loads"- 如何解决这个错误?

mysql - Golang JSON 编码将表情符号转换为问号

javascript - 更新变量时动态刷新模板的一部分golang

windows - TerminateProcess() 返回 EINVAL

string - Go,从字节数组中提取天数

在 Windows 10 64 位分割错误上使用 Fitz 将 PDF 转换为图像

json - 即使存在值,Go map 也会返回 nil 值

deployment - 部署 Go 应用程序

SSH 连接超时

arrays - 如何在golang中创建对象数组?