加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang获取特定结构字段名称的字符串表示

发布时间:2020-12-16 09:22:23 所属栏目:大数据 来源:网络整理
导读:我真的想要一种在go中打印字段名称的字符串表示的方法.它有几个用例,但这里有一个例子: 假设我有一个结构 type Test struct { Field string `bson:"Field" json:"field"` OtherField int `bson:"OtherField" json:"otherField"`} 并且,例如,我想做一个mongo
我真的想要一种在go中打印字段名称的字符串表示的方法.它有几个用例,但这里有一个例子:

假设我有一个结构

type Test struct {
    Field      string `bson:"Field" json:"field"`
    OtherField int    `bson:"OtherField" json:"otherField"`
}

并且,例如,我想做一个mongo find:

collection.Find(bson.M{"OtherField": someValue})

我不喜欢我必须把字符串“OtherField”放在那里.它似乎很脆弱,容易错误排序或更改结构,然后我的查询失败,而我不知道它.

有没有办法得到字符串“OtherField”而不必声明const或类似的东西?我知道我可以使用反射来获取结构中的字段名称列表,但我真的很想做一些事情.

fieldName := nameOf(Test{}.OtherField) 
collection.Find(bson.M{fieldName: someValue})

Go有没有办法做到这一点? C#6有内置名称,但是通过反思挖掘我在Go中找不到任何方法.

解决方法

我真的不认为有.您可以通过反射加载一组类型,并为字段名称生成一组常量.所以:

type Test struct {
    Field      string `bson:"Field" json:"field"`
    OtherField int    `bson:"OtherField" json:"otherField"`
}

可以产生类似的东西:

var TestFields = struct{
      Field string
      OtherField string
}{"Field","OtherField"}

你可以使用TestFields.Field作为常量.

不幸的是,我不知道有任何类似的现有工具.做起来相当简单,然后通过电线连接生成.

编辑:

我是如何生成它的:

>创建一个接受reflect.Type或interface {}数组的包,并吐出一个代码文件.
>使用main函数在repo中的某处创建generate.go:

func main(){
   var text = mygenerator.Gen(Test{},OtherStruct{},...)
   // write text to constants.go or something
}

>添加// go:生成go run scripts / generate.go到我的主应用程序并运行go generate

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读