dongmangji0950 2019-03-18 09:06
浏览 94

如何省略杜松子酒结构的一些参数

I have big structure with more than 50 params

type Application struct {
    Id                  int64   `json:"id"`
    FullName            string  `json:"fullName,omitempty"`
    ActualAddress       string  `json:"actualAddress,omitempty"`
.....
}

I use gin-gonic and when I return application I need to omit some params I've created a function which makes empty some params (playLink) and then gin returns me correct json (without unnecessary values). I heard that reflection isn't fast operation so in our case we can use a lot of ugly if-else or switch-cases. Is there any other solutions faster than reflecting and more beautiful than if-elses?

The thing is that structure params have non-empty values, so they wont by omitted by gin. That's why I've created function to make some params empty before return

  • 写回答

2条回答 默认 最新

  • douhuan1380 2019-03-18 09:21
    关注

    The thing is, if you only want to zero a few fields, it's more readable to do it without a function, e.g.

    app := Application{}
    
    app.FullName, app.ActualAddress = "", ""
    

    If you want to create a function for it, at least use variadic parameter, so it's easier to call it:

    func zeroFields(application *Application, fields ...string) {
        // ...
    }
    

    So then calling it:

    zeroFields(&app, "FullName", "ActualAddress")
    

    Yes, this will have to use reflection, so it's slower than it could be, and error prone (mistyped names can only be detected at runtime). If you want to avoid using reflection, pass the address of the fields:

    func zeroFields(ps ...*string) {
        for _, p := range ps {
            *p = ""
        }
    }
    

    This way you have compile-time guarantee that you type field names correctly, and that they have string type.

    Calling it:

    zeroFields(&application.FullName, &application.ActualAddress)
    

    Try it on the Go Playground.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图