dongwei5740 2019-01-03 07:35
浏览 9

Linter检查结构初始化中是否显式设置了所有字段

I want to have a static assert or linter for my go code that checks that I do not – by mistake – initialise the structs in my config file with default values for any field. I want everything to be set explicitly.

Is there a way to achieve this?

EDIT: Clarified question.

  • 写回答

1条回答 默认 最新

  • dougaoshang0237 2019-01-03 07:53
    关注

    Check out the validator package. https://gopkg.in/go-playground/validator.v9

    We use it extensively in our code to validate structs. e.g.

    type Config struct {
      Url      string  `validate:"required"`
      MaxHops  int     `validate:"omitempty,min=0"`
      MaxTerms int     `validate:"omitempty,min=0"`
      MaxCost  float64 `validate:"omitempty,min=0"`
    }
    
    func Init(cfg *Config) error {
      if err := validator.New().Struct(cfg); err != nil {
        return errors.Wrap(err, "error in config")
      }
      //do something
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大