避免裸参数

函数调用中的裸参数可能会降低代码可读性。所以当参数名称的含义不明显时,请为参数添加 C 样式的注释(//)。

BadGood
  1. // func printInfo(name string, isLocal, done bool)
  2. printInfo("foo", true, true)
  1. // func printInfo(name string, isLocal, done bool)
  2. printInfo("foo", true / isLocal /, true / done /)

上面更好的作法是将 bool 类型替换为自定义类型,从而使代码更易读且类型安全。将来需要拓展时,该参数也可以不止两个状态(true/false)。

  1. type Region int
  2. const (
  3. UnknownRegion Region = iota
  4. Local
  5. )
  6. type Status int
  7. const (
  8. StatusReady = iota + 1
  9. StatusDone
  10. // 也许将来我们会有 StatusInProgress。
  11. )
  12. func printInfo(name string, region Region, status Status)