[英]How to use Golang Reflection to get the type of a struct field that is a slice?
[英]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)
}
去運行main.go
名稱:Id類型:int64類型:int64
名稱:名稱類型:字符串類型:字符串
名稱:角色類型: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值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.