douyun8901 2017-12-15 22:23
浏览 46
已采纳

if序列可以更优美地编写吗? [关闭]

if v, ok := os.LookupEnv("IDAASHTTPPORT"); ok {
    c.HTTPPort, _ = strconv.Atoi(v)
}
if v, ok := os.LookupEnv("IDAASDBNAME"); ok {
    c.DBUserName = v
}
if v, ok := os.LookupEnv("IDAASDBPW"); ok {
    c.DBPasswd = v
}
if v, ok := os.LookupEnv("IDAASDBPORT"); ok {
    c.DBPort, _ = strconv.Atoi(v)
}
if v, ok := os.LookupEnv("IDAASDBHOST"); ok {
    c.DBHost = v
}

'c' is the following struct

type Configuration struct {
    HTTPPort   int
    DBUserName string
    DBPasswd   string
    DBPort     int
    DBHost     string
}

I only want to update the struct field if the environment variable exists. Seems like some little cute map iterator or something like that would work, but I can't figure out a nice solution.

  • 写回答

1条回答 默认 最新

  • dongyupen6269 2017-12-15 22:53
    关注

    You can use some helper functions:

    func setIntFromEnv(val *int, envName string) {
      if v, ok := os.LookupEnv(envName); ok {
        *val, _ = strconv.Atoi(v)
      }
    }
    
    func setStringFromEnv(val *string, envName string) {
      if v, ok := os.LookupEnv(envName); ok {
        *val = v
      }
    }
    
    // From your main function.
    setIntFromEnv(&c.HTTPPort, "IDAASHTTPPORT")
    setStringFromEnv(&c.DBUserName, "IDAASDBNAME")
    etc...
    

    This only works if you're ok ignoring a string env var that you're trying to parse as an int. Its relative elegance is also debatable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图