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/