Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract FIELD names of a struct and put them in a slice of strings

Tags:

struct

go

raylib

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
}
like image 987
nicholasimon Avatar asked Oct 21 '25 16:10

nicholasimon


1 Answers

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?

like image 60
icza Avatar answered Oct 23 '25 06:10

icza