Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if type is a struct

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 = "[email protected]"
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))
  }
}
like image 760
Ferry Sutanto Avatar asked Feb 06 '17 10:02

Ferry Sutanto


Video Answer


1 Answers

Just check the Kind() of Value

if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
    fmt.Println(reflect.ValueOf(e).Field(i))
}
like image 188
Uvelichitel Avatar answered Oct 22 '22 15:10

Uvelichitel