Golang Variable Naming Convention [Tutorial]


Written By - Tuan Nguyen
Advertisement

In this post, I would like to provide some simple rules so that you can name your code easier and avoid endless arguments with your colleagues about naming conventions.
Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case. It's therefore worth spending a little time talking about naming conventions in Go programs.

Package names

The package name becomes an accessor for the contents when a package is imported. Everyone using the package should be able to refer to its contents using the same name, hence the package name should be appropriate: short, concise, evocative. 

By convention, package names are written in lower case and consist of a single word; there shouldn't be a need for underscores or mixed caps. Don't stress out in advance about collisions. The package name is merely the imports' default name; it is not required to be unique throughout all source code, and in the unlikely event of a clash, the importing package may select a different name to use locally. In any case, confusion is uncommon because the import's file name specifies precisely which package is being used.

Another convention is that the package name is the base name of its source directory; the package in src/encoding/base64 is imported as "encoding/base64" but has name base64, not encoding_base64 or encodingBase64.

Interface names

By convention, Reader, Writer, Formatter, CloseNotifier, etc. are examples of inteface names created for one-method interfaces by combining the method name with a -er suffix or other equivalent alteration.

There are several of these names, and it is beneficial to respect them and the function names they identify. There are standard signatures and semantics for Read, Write, Close, Flush, String and other words. Give your method a different name unless it has the same signature and semantics in order to avoid misunderstanding. On the other hand, if your type implements a method that has the same meaning as a method on another type that is widely used, give it the same name and signature; call your method for converting strings String rather than ToString.

Naming Convention for Files

  • Go adheres to a practice in which source files are all written in lower case and multiple words are separated by underscores.
  • Compound file names are separated by _
  • The go tool ignores file names that start with "." or " ."
  • Only the go test tool can compile and execute files with the _test.go suffix.

Defining Functions and Methods

Use miexedCaps as introduced above, exported functions should start with uppercase:

writeToExcel      // unexported, only visible within the package
WriteToExcel     // exported, visible within the package

Defining constants and variables

Constants

Constant should separate words with an underscore (_), and use all capital letters.

Advertisement

Example of declaring constant in Go:

const Pi = 3.14
const MY_INT_CONST int = 20 

Variables

A variable can have a short name (like x and y) or a more descriptive name (age, price, carname, etc.).

Rules for go variable naming

  • A variable name must be preceded by a letter or the underscore symbol (_).
  • The first digit of a variable name cannot be used.
  • Only underscores (_, a-z, a-z, 0-9, and a-z) and alphanumeric characters are permitted in variable names.
  • Names of variables are case-sensitive (age, Age and AGE are three different variables)
  • The variable name can be as long as you want.
  • No slashes are permitted in variable names.
  • The variable name cannot be any Go keywords

Some rules can be apply for the more readability:

  • If variable type is bool, its name should start with Has, Is, Can or Allow, etc.
  • Single letter represents index: i, j, k

Multiple-word variable names can be challenging to read. For this case, you can use several techniques to make them more readable, but it should be noted that use a consistent naming style in the entire source code.

Case handling the idiomatic way!

Finally, the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names.

MixedCaps (Camel Case)

Each word, except the first, starts with a capital letter:

variableName := "Harry Potter" 
variableAge := 20

MixedCaps (Pascal Case)

Pascal casing is a style of code formatting in which you concatenate capitalized words: ThisIsPascalCasing.

VariableName := "Harry Potter" 
VariableAge := 20

Snake Case (not recommended)

Even though underscore is a valid character in a variable name, it is rarely used, because idiomatic Go doesn’t use snake case (names like index_counter or number_tries). Instead, idiomatic Go uses camel case (names like indexCounter or numberTries) when an identifier name consists of multiple words.

variable_name := "Harry Potter" 
varibale_age := 20

Summary

Readability is essential for maintainability.
— Mark ReinholdJVM language summit 2018

The most important skill for a programmer is the ability to effectively communicate ideas.
— Gastón Jorquera

Writing clean and readable code is not an easy task. It requires you to keep reading about good practices and apply them as much as you can to avoid the bad ones.

Now you understand why following naming conventions is essential, and although it seems like a trivial task, it really contributes to your projects. If you know any other advantage for following naming conventions, please share it with us.

References

https://go.dev/doc/effective_go
https://en.wikipedia.org/wiki/Naming_convention_(programming)

Categories GO

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

2 thoughts on “Golang Variable Naming Convention [Tutorial]”

  1. Hi Tuan. I found this to be very helpful. I’ve had a hard time finding suggestions on specific variable naming conventions for Go, which is funny because most of what we name are variables. . . Anyway, small error, your example for Camel Case and Pascal Case are the same. Camel case is:

       VariableName := "Harry Potter" 
       VariableAge := 20

    but should be:

       variableName := "Harry Potter" 
       variableAge := 20
    Reply

Leave a Comment