How to check specific field exist in struct?
The below code snippet declares a struct type Test with fields A, B, and C. We need to verify field Z exists in struct type Test or not.
Example
package main
import (
"log"
"reflect"
)
func main() {
type test struct {
A bool
B bool
C bool
}
v := new(test)
metaValue := reflect.ValueOf(v).Elem()
for _, name := range []string{"A", "C", "Z"} {
field := metaValue.FieldByName(name)
if field == (reflect.Value{}) {
log.Printf("Field %s not exist in struct", name)
}
}
}
2009/11/10 23:00:00 Field Z not exist in struct
Most Helpful This Week
How to create Slice of Struct in Golang?
How to initialize a struct containing a slice of structs in Golang?
How to build a map of struct and append values to it?
Concurrently printing array elements using goroutines and channels
How to convert Struct fields into Map String?
Golang panic recover example
How do you catch panic in Golang?
How to append struct member dynamically using Empty Interface?