SoFunction
Updated on 2025-03-04

Variable naming rules and examples in Go

Preface

Andrew Gerrand from Google once shared about the parameter naming specification in Go, slides is /2014/

Naming habits are important

  • Good readability is one of the requirements for high-quality code
  • Good naming habits help improve code readability

Good name favorite traits

Good Name will have the following traits:

  • Consistent (easy to guess),
  • Short (easy to type),
  • Accurate (easy to understand)

Rules of thumb

The further the variable declaration and the use of the variable, the longer the variable name should be.

This also explains why the for loop variable uses i as a temporary variable for traversal, rather than a semantically more specific index as the variable name.

Variable names that are mixed with upper and lower case

We should not use names_with_underscores as variable name, but namesWithUnderscores as variable name.

On the other hand, the acronym should be capitalized, such as ServeHTTP and IDProcessor.

This is called MixedCase, similar to the camel principle naming, but the acronyms of professional vocabulary should be written in capital.

Variable names avoid redundancy

The longer the variable name, the better, the normal variable name will blur the code function.

Common constants and types combinations may use very short names:

  • Use i instead of index
  • Use r instead of reader
  • Use b instead of buffer

Depending on the context, avoid redundant names:

  • Inside the RuneCount method, use count instead of reuneCount
  • In the map statement, use ok instead of keyInMap:
v, ok := m[k]

A constant variable name may be helpful in long functions, functions with many variables, but this usually also means you should refactor the code.

Bad codes vs good codes

// Bad
func RuneCount(buffer []byte) int {
      // runeCount -> count
    runeCount := 0
      // index -> i , buffer -> b
    for index := 0; index < len(buffer); {
        if buffer[index] < RuneSelf {
            index++
        } else {
              // size -> n
            _, size := DecodeRune(buffer[index:])
            index += size
        }
        runeCount++
    }
    return runeCount
}
// Good
func RuneCount(b []byte) int {
    count := 0
    for i := 0; i < len(b); {
        if b[i] < RuneSelf {
            i++
        } else {
            _, n := DecodeRune(b[i:])
            i += n
        }
        count++
    }
    return count
}

Naming of function parameters

Function parameters, like variable names, play a role in the document.

1. When the type of function parameter is descriptive, the function parameter name can be shorter:

func AfterFunc(d Duration, f func()) *Timer
func Escape(w , s []byte)

2. When the type of function parameters is not clear, the parameter name should be more specific and detailed:

func Unix(sec, nsec int64) Time
​​​​​​​func HasPrefix(s, prefix []byte) bool

Name of return value

The exported function return value should be named for the purpose of writing the document only.

Here are good examples of return value naming:

// Good
func Copy(dst Writer, src Reader) (written int64, err error)
// Good
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)

Naming of method Receiver

In Go, structures can have methods. When declaring methods for structures, structures are called receivers.

By convention, the name of the method receiver is usually 1 character or 2 characters, because each method of the structure will use the same receiver name.

// Good
func (b *Buffer) Read(p []byte) (n int, err error)
// Good
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request)
// Good
func (r Rectangle) Size() Point

The name of the Receiver must be consistent. If the method1 of the structure uses r as the receiver name, then method2 should not use rdr as the name.

Export package-level variable naming

Variables at the package level have been limited by package name, so you need to pay attention to the redundancy of exporting variables, constants, functions, and type names.

For example:

  • We use instead
  • We use instead

Do not have redundancy between export variable names and packages.

Interface type

There is only one method interface, and the interface name is usually simply added with er after the method to perform commands, for example:

type Reader interface {
    Read(p []byte) (n int, err error)
}

Sometimes, the above strategy will cause the interface name syntax to be incorrect, but we can still choose to do this, for example:

type Execer interface {
    Exec(query string, args []Value) (Result, error)
}

Sometimes, we modify the interface name to conform to the English syntax:

type ByteReader interface {
    ReadByte() (c byte, err error)
}

When an interface contains multiple methods, a name that accurately describes its purpose should be selected, for example, ,.

error naming

Error types and error variables should have different naming formats:

// Error type Error typestype ExitError struct {
    ...
}
// Error variable Error valuesvar ErrFormat = ("image: unknown format")

Packages name

Select a package name that has meaning to the exported name.

Avoid using package names such as util and common.

in conclusion

Use short variable names

Variable name considers context and avoids redundancy. For example, local variables in functions take into account function names, and package export variables take into account package names.

Summarize

This is the end of this article about variable naming in Go. For more related Go variable naming content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!