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 read names of all files and folders in current directory?
Exploring Blockchain: Top 15 Real-World Use Cases in 2024
Golang program for implementation LZW Data Compression and Uncompression
How to remove special characters from a string in GoLang?
What is Struct
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)