10

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)) } } 
1
  • 3
    Please see stackoverflow.com/help/how-to-ask for quidlines on how to ask a good question. Your post doesn't actually ask a question. Commented Feb 6, 2017 at 10:25

2 Answers 2

29

Just check the Kind() of Value

if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct { fmt.Println(reflect.ValueOf(e).Field(i)) } 
Sign up to request clarification or add additional context in comments.

1 Comment

Seems taking Type is not necessary cause Value has Kind() on its own as well.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.