如何确定type是否是Golang中的结构

时间:2017-02-06 10:15:21

标签: go reflection struct

假设我有两个结构:

type Base struct {
 id int
 name string
}

type Extended struct {
 Base
 Email string
 Password string
}

我想反映Extended struct来获取它的字段:

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 个答案:

答案 0 :(得分:7)

只需检查值的种类()

if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
    fmt.Println(reflect.ValueOf(e).Field(i))
}