2

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
}
icza
  • 389,944
  • 63
  • 907
  • 827
nicholasimon
  • 75
  • 1
  • 7

1 Answers1

3

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • That worked absolutely perfectly and was exactly what I wanted, thanks. If I want a list of field types as strings how would I do that? For example [int float32 string int] so instead of the names in the slice, it is the field type as a string in the slice? – nicholasimon May 20 '21 at 16:00
  • 1
    If you only want to add `string` fields, then check the type's kind: `t.Field(i).Type.Kind() == reflect.String`. – icza May 21 '21 at 08:51