In Go, the convention for casing variable names follows these general rules:
-
Exported Identifiers (Global): If a variable, constant, type, or function is intended to be used outside of its own package, its name should start with an uppercase letter. This is sometimes referred to as "Title Case" or "Pascal Case". This is how you export identifiers in Go - there is no public or export keyword like in some other languages.
-
Unexported Identifiers (Private): If the identifier is not intended to be used outside of its own package, it should start with a lowercase letter.
-
Camel Case: Both exported and unexported variable names should be written in camel case, where each new word begins with a capital letter and the first word starts with a lowercase or uppercase letter depending on whether the variable is unexported or exported, respectively. For example, localVariable for an unexported variable and GlobalVariable for an exported one.
-
Constants: Constants follow the same naming conventions as variables in terms of case sensitivity. Exported constants should start with an uppercase letter, while unexported constants should start with a lowercase letter, and camel case should be used. For example, const LocalConst = "foo" for an unexported constant and const GlobalConst = "bar" for an exported one.
-
Acronyms and Initialisms: When a name contains an acronym or initialism, the Go convention is to keep the acronym uppercase (if the entire variable name is an acronym) or to capitalize it as a block if it's part of a longer name. For example, HTTPServer is an exported name, and httpRequest is an unexported name.
-
Snake Case: Snake case (snake_case) is not commonly used in Go for variable names or constants. It's more typical in languages like Python and Ruby.
Here are some examples that follow Go naming conventions:
// Exported variable:
var GlobalVariable int
// Unexported variable:
var localVariable int
// Exported constant:
const MaxSize = 1024
// Unexported constant:
const minSize = 1
// Exported function:
func ComputeHash() string {
// ...
}
// Unexported function:
func computeSum() int {
// ...
}
In summary, for Go variable and constant names, you should use camel case, with the appropriate case for the first letter depending on whether the identifier is exported or unexported. Avoid using snake case for Go code.