I want to be able to extract the FIELD names (not the values) of a struct as strings, put them in a slice of strings and then use the names to print in a menu in Raylib (a graphics library for Go) elsewhere in a program. That way if I change the fields in the struct the menu will update automatically without having to go back and manually edit it. So, if you take a look at the struct below, I want to extract the names MOVING, SOLID, OUTLINE etc. not the boolean value. Is there a way to do this?
type genatt struc {
moving, solid, outline, gradient, rotating bool
}
You may use reflection (reflect package) to do this. Acquire the reflect.Type descriptor of the struct value, and use Type.Field() to access the fields.
For example:
t := reflect.TypeOf(genatt{})
names := make([]string, t.NumField())
for i := range names {
names[i] = t.Field(i).Name
}
fmt.Println(names)
This will output (try it on the Go Playground):
[moving solid outline gradient rotating]
See related questions:
How to get all Fields names in golang proto generated complex structs
How to sort struct fields in alphabetical order
What are the use(s) for tags in Go?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With