简体   繁体   中英

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

Just check the Kind() of Value

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

Can also use type switch:

switch i := x.(type) {
case nil:
    printString("x is nil")                // type of i is type of x (interface{})
case int:
    printInt(i)                            // type of i is int
case float64:
    printFloat64(i)                        // type of i is float64
case func(int) float64:
    printFunction(i)                       // type of i is func(int) float64
case bool, string:
    printString("type is bool or string")  // type of i is type of x (interface{})
default:
    printString("don't know the type")     // type of i is type of x (interface{})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM