类似的Golang变量的命名约定

huangapple go评论81阅读模式
英文:

Naming convention for similar Golang variables

问题

我有几个情况,其中同一个基础值被表示为多种类型。

示例:

userIDString := r.URL.Query("id")
userID, err := strconv.Atoi(userIDString)

我需要在不同的地方使用上述两个变量。

类似地,

recordSeparator = rune(30)
recordSeparatorString = string(30)

我命名这种变量的方法是否符合 Go 的惯例?如果不符合,针对这种情况的理想命名约定是什么?

附注:我认为这个问题不是主观的,我正在寻找参考流行的 Go 项目/标准库中的命名约定的答案。

英文:

I have a couple of cases where I have the same underlying value being represented as multiple types.

Example :

userIDString := r.URL.Query("id")
userID, err :=  strconv.Atoi(userIDString)

I need to use both the above variables at different places.

Similarly

recordSeparator = rune(30)
recordSeparatorString = string(30)

Is my approach to naming such variables considered idiomatic go ? If not what would be the ideal naming convention for such cases ?

PS: I don't think this question is primarily opinion based, I'm looking for answers referencing the naming conventions in popular go projects / standard lib.

答案1

得分: 13

在该领域中,最有权威性的书籍可能是《Go程序设计语言》。该书在第10.6节“包和命名”中讨论了这个主题:

  • 名称要保持简短,但不要使它们晦涩难懂(使用user而不是userName)。
  • 包名通常采用单数形式(除非与预声明类型冲突)。
  • 选择名称时要考虑包的上下文,例如,net.IP

此外,还有一个很好的幻灯片《名字中有什么》,其中涉及了一些问题,还有一个相对信息丰富的Reddit帖子也可能有用。

根据我的经验,大部分命名约定(除了上述提到的)都是项目或公司特定的。

英文:

The likely most authoritative book in the field, The Go Programming Language, discusses this topic in section 10.6 Packages and Naming:

  • keep names short but don't make them cryptic (user over userName)
  • package names usually take singular form (unless there's a conflict with predeclared types)
  • pick names so that they read in the context of the package, for example, net.IP

In addition, there's a nice slide deck What's in a name addressing some of the questions and a somewhat informative reddit thread that might be useful as well.

Most of the naming conventions in my experience (in addition to the above mentioned) are however project or company specific.

huangapple
  • 本文由 发表于 2016年11月30日 14:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/40881994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定