提取结构体的字段名称,并将它们放入一个字符串切片中。

huangapple go评论140阅读模式
英文:

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/57885851/how-to-get-all-fields-names-in-golang-proto-generated-complex-structs/57886310#57886310

https://stackoverflow.com/questions/30913483/how-to-sort-struct-fields-in-alphabetical-order/30915092#30915092

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/57885851/how-to-get-all-fields-names-in-golang-proto-generated-complex-structs/57886310#57886310

https://stackoverflow.com/questions/30913483/how-to-sort-struct-fields-in-alphabetical-order/30915092#30915092

https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373

huangapple
  • 本文由 发表于 2021年5月20日 01:44:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/67608323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定