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.
In Golang, any variable (or a function) with an identifier starting with an upper-case letter (example, CamelCase) is made public (accessible) to all other packages in your program, whereas those starting with a lower-case letter (example, camelCase) is not accessible to any package except the one it is being declared ...
The choice of a variable name should be mnemonic — that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)
You don't need to go through the whole code to find their meaning, just through the current scope/code block. Variable names in Go should be short rather than long. This is especially true for local variables with limited scope.
The likely most authoritative book in the field, The Go Programming Language, discusses this topic in section 10.6 Packages and Naming:
user
over userName
)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With