Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for similar Golang variables

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.

like image 590
John S Perayil Avatar asked Nov 30 '16 06:11

John S Perayil


People also ask

How do you name variables in Golang?

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 ...

Which is a correct naming convention for a variable?

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.

What are the 3 rules that need to be considered while naming a variable?

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)

Why does Golang prefer short variable names?

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.


1 Answers

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.

like image 152
Michael Hausenblas Avatar answered Oct 02 '22 08:10

Michael Hausenblas