Go naming conventions allow writing clear, concise, and consistent code. Here are some guidelines:
File Names
File names should be in lowercase and should contain underscores. For example main.go
, server.go
.
Package Names
Package names should be short, lowercase, and without underscores or mixed caps. Typically, package names are single words. For example:
package io
Code language: Go (go)
Variable names
Use camelCase
for private variables and functions:
var total float64 = 0
func calculateTotal() int {
// function body
}
Code language: Go (go)
Use PascalCase
for exported (public) variables and functions. For example:
var Area float64 = 0.0
func CalculateCircleArea(radius float64) float64 {
// function body
}
Code language: Go (go)
Constants
- Use
camelCase
for unexported constants, for example,taxRate
andPascalCase
for exported constants such asTaxRate
- Prefer all uppercase with underscores for constant groups.
Types
Use PascalCase
for type names such as Customer
and BankAccount
.
Structs
Use PascalCase
for exported structs and camelCase
for private structs. For example:
type Person struct {
FirstName string
LastName string
Age int
}
Code language: Go (go)
Similarly, use PascalCase
for exported fields and camelCase
for private fields.
Methods
Use the receiver’s type name (or its first letter) as the method receiver name. For example:
func (p Person) GetFullName () string {
return p.FirstName + " " + p.LastName
}
Code language: Go (go)
Interfaces
Name interfaces based on the behavior they describe, usually ending in -er
. For example: FileReader
, Parser
:
interface Formater {
GetFullName() string
}
Code language: Go (go)
Acronyms
Capitalize acronyms consistently. For example: HTTP
, URL
, JSON
should be HttpRequest
, UrlParser
, JsonEncoder
.
Package-Level Variables
Avoid using package-level variables whenever possible.
When necessary, use descriptive names in camelCase
or PascalCase
depending on the export status. For example:
var defaultTimeout = 5 * time.Second
var DefaultTimeout = 5 * time.Second
Code language: Go (go)