英文:
Extract FIELD names of a struct and put them in a slice of strings
问题
我想要能够将结构体的字段名(而不是值)作为字符串提取出来,将它们放入一个字符串切片中,然后在程序的其他地方使用这些字段名来打印一个菜单在Raylib(一个用于Go的图形库)中。这样,如果我更改结构体中的字段,菜单将自动更新,而无需返回并手动编辑它。所以,如果你看一下下面的结构体,我想提取出MOVING、SOLID、OUTLINE等字段名,而不是布尔值。有没有办法做到这一点?
type genatt struct {
moving, solid, outline, gradient, rotating bool
}
英文:
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
}
答案1
得分: 3
你可以使用反射(reflect
包)来实现这个。获取结构体值的reflect.Type
描述符,并使用Type.Field()
来访问字段。
例如:
t := reflect.TypeOf(genatt{})
names := make([]string, t.NumField())
for i := range names {
names[i] = t.Field(i).Name
}
fmt.Println(names)
这将输出(在Go Playground上尝试):
[moving solid outline gradient rotating]
相关问题请参考:
https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373
英文:
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:
https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论