Ferry Sutanto
Ferry Sutanto

Reputation: 119

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

Upvotes: 10

Views: 21005

Answers (2)

Vladislav Popovici
Vladislav Popovici

Reputation: 35

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

Upvotes: 1

Uvelichitel
Uvelichitel

Reputation: 8490

Just check the Kind() of Value

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

Upvotes: 29

Related Questions