Home > Mobile >  Calling NumField on Value panics in some cases (go)
Calling NumField on Value panics in some cases (go)

Time:03-19

I'm using reflect.ValueOf(..) to loop through elements in a struct. I noticed that calling NumField fails if i pass the struct vs. pointer to the struct in the ValueOf function.

v = reflect.ValueOf(user)
v.NumField() // panics

Vs.

v = reflect.ValueOf(*user)
v.NumField() // works

Is there a way to find out beforehand if v would panic, before calling NumField?

CodePudding user response:

You have to check the ‘Kind’ to ensure it’s a structure.

CodePudding user response:

Use reflect.Indirect to handle both cases in the question:

v := reflect.Indirect(reflect.ValueOf(x))
v.NumField()

The NumField documentation says:

It panics if v's Kind is not Struct.

Check the kind to avoid the panic:

if v.Kind() == reflect.Struct {
   v.NumField()
} else {
   // do something else
}
  • Related