Fuz*_*ker 4 reflection go field-names
我真的想要一种在go中打印字段名称的字符串表示的方法.它有几个用例,但这里有一个例子:
假设我有一个结构
type Test struct {
Field string `bson:"Field" json:"field"`
OtherField int `bson:"OtherField" json:"otherField"`
}
Run Code Online (Sandbox Code Playgroud)
并且,例如,我想做一个mongo find:
collection.Find(bson.M{"OtherField": someValue})
Run Code Online (Sandbox Code Playgroud)
我不喜欢我必须把字符串"OtherField"放在那里.它似乎很脆弱,容易错误排序或更改结构,然后我的查询失败,而我不知道它.
有没有办法得到字符串"OtherField"而不必声明const或类似的东西?我知道我可以使用反射来获取结构中的字段名称列表,但我真的很想做一些事情.
fieldName := nameOf(Test{}.OtherField)
collection.Find(bson.M{fieldName: someValue})
Run Code Online (Sandbox Code Playgroud)
Go有没有办法做到这一点?C#6有内置名称,但是通过反思挖掘我在Go中找不到任何方法.
我真的不认为有.您可以通过反射加载一组类型,并为字段名称生成一组常量.所以:
type Test struct {
Field string `bson:"Field" json:"field"`
OtherField int `bson:"OtherField" json:"otherField"`
}
Run Code Online (Sandbox Code Playgroud)
可以产生类似的东西:
var TestFields = struct{
Field string
OtherField string
}{"Field","OtherField"}
Run Code Online (Sandbox Code Playgroud)
你可以TestFields.Field用作常数.
不幸的是,我不知道有任何类似的现有工具.做起来相当简单,然后连线go generate.
编辑:
我是如何生成它的:
reflect.Type或多个数组的包,interface{}并吐出一个代码文件.generate.go使用main函数在我的repo中创建一个地方:
func main(){
var text = mygenerator.Gen(Test{}, OtherStruct{}, ...)
// write text to constants.go or something
}
Run Code Online (Sandbox Code Playgroud)//go:generate go run scripts/generate.go到我的主应用程序并运行go generate