doushi1974 2017-05-04 19:44
浏览 397
已采纳

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

I really want a way to print the string representation of a field name in go. It has several use cases, but here is an example:

lets say I have a struct

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

and, for example, I want to do a mongo find:

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

I don't like that I have to put the string "OtherField" in there. It seems brittle and easy to either misstype or have the struct change and then my query fails without me knowing it.

Is there any way to get the string "OtherField" without having to either declare a const or something like that? I know I can use reflection to a get a list of field names from a struct, but I'd really like to do something along the lines of

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

is there any way to do this in Go?? C# 6 has the built in nameof, but digging through reflection I can't find any way to do this in Go.

  • 写回答

2条回答 默认 最新

  • douzhicai7148 2017-05-04 19:54
    关注

    I don't really think there is. You may be able to load a set of types via reflection and generate a set of constants for the field names. So:

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

    Could generate something like:

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

    and you could use TestFields.Field as a constant.

    Unfortunately, I don't know of any existing tool that does anything like that. Would be fairly simple to do, and wire up to go generate though.

    EDIT:

    How I'd generate it:

    1. Make a package that accepts an array of reflect.Type or interface{} and spits out a code file.
    2. Make a generate.go somewhere in my repo with main function:

      func main(){
         var text = mygenerator.Gen(Test{}, OtherStruct{}, ...)
         // write text to constants.go or something
      }
      
    3. Add //go:generate go run scripts/generate.go to my main app and run go generate
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题