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