Go by Example: Naming Conventions
Go has strict and opinionated naming conventions that directly affect symbol visibility and code readability. This example covers `MixedCaps`, package naming, interface naming, and the "Effective Go" guidelines for variable length.
Code
package main
import (
"fmt"
"strings"
)
// Exported types and fields use MixedCaps (start with uppercase).
// They are visible outside the package.
type UserConfig struct {
APIKey string // Exported field
timeout int // Unexported field (lowercase start)
}
// Interfaces ending in a single method are often named with an -er suffix.
type Printer interface {
Print()
}
// Getters should not include "Get" in the name.
// Just use the name of the field (capitalized).
func (u *UserConfig) Timeout() int {
return u.timeout
}
// Setters can use "Set" prefix.
func (u *UserConfig) SetTimeout(ms int) {
u.timeout = ms
}
func main() {
// Local variables should be short and concise.
// 'cfg' is better than 'userConfiguration' for a small scope.
cfg := &UserConfig{
APIKey: "secret-123",
timeout: 5000,
}
fmt.Printf("Timeout: %dms\n", cfg.Timeout())
// Acronyms should be all uppercase (e.g., 'API', 'URL', 'ID').
// Bad: parseUrl, userId
// Good: ParseURL, UserID
userID := 42
fmt.Println("User ID:", userID)
// Package names (like 'fmt' or 'strings') are always lowercase,
// single-word, and usually singular.
fmt.Println(strings.ToUpper("hello"))
}
Explanation
Go's naming conventions are more than just style preferences; they determine the visibility of your identifiers. A name starting with an uppercase letter is exported (public) and accessible from other packages. A name starting with a lowercase letter is unexported (private) and visible only within its own package. This simple rule eliminates the need for keywords like public or private.
For multi-word names, Go uses MixedCaps (CamelCase) rather than underscores (snake_case). This applies to variables, functions, structs, and interfaces. Another key convention from "Effective Go" is that variable names should be short rather than long. The smaller the scope of a variable, the shorter its name should be. For example, i is perfect for a loop index, while serverTimeout is appropriate for a global configuration.
Specific idioms include:
- Packages: Short, lowercase, single-word names (e.g.,
time,list). Avoidutilsorcommon. - Interfaces: Single-method interfaces end in
-er(e.g.,Reader,Writer). - Getters: Do not use "Get" prefix. If field is
owner, getter isOwner(). - Acronyms: Keep them uppercase (e.g.,
ServeHTTP, notServeHttp).

