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
Golang HTTP GET request with parameters
GO Program to find area and circumference of circle
Missing return at end of function error in Golang
GO Program to Generate Multiplication Table
How to append struct member dynamically using Empty Interface?
Illustration of Cigarette Smokers Problem in Golang