问题
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:
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
overuserName
) - 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.
来源:https://stackoverflow.com/questions/40881994/naming-convention-for-similar-golang-variables