如何确定类型是否为结构体 [英] How to determine if type is a struct
本文介绍了如何确定类型是否为结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 2 个结构:
Suppose I have 2 structs:
type Base struct {
id int
name string
}
type Extended struct {
Base
Email string
Password string
}
我想反映扩展结构以获取它的字段:
And i want to reflect the Extended struct to get it's field :
e := Extended{}
e.Email = "me@mail.com"
e.Password = "secret"
for i := 0 ; i < reflect.TypeOf(e).NumField() ; i++ {
if reflect.TypeOf(e).Field(i) != "struct" { << how to do this validation?
fmt.Println(reflect.ValueOf(e).Field(i))
}
}
推荐答案
只需检查 Kind() of Value
Just check the Kind() of Value
if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
fmt.Println(reflect.ValueOf(e).Field(i))
}
这篇关于如何确定类型是否为结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文