How to determine if type is a struct in Golang

2019-04-17 10:35发布

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

1条回答
走好不送
2楼-- · 2019-04-17 11:06

Just check the Kind() of Value

if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
    fmt.Println(reflect.ValueOf(e).Field(i))
}
查看更多
登录 后发表回答