This document outlines common naming conventions used in Go projects. These conventions follow recommendations from Effective Go and widely adopted industry practices.
Naming convention#
- Standard naming convention followed for variables, functions etc.
- Any Identifier which starts with a Capital-Case are exported & available outside the defining package.
- MixedCase is followed i.e
- camelCase for identifiers (non-exported ones i.e only available within the package)
- PascalCase for identifiers (exported ones i.e also available outside the package)
// Exported as the first character is capital 'E'.
var ExportedVariable int
// Non Exported identifier & only accessible within the package.
var nonExportedVariable intPackage Naming Practices#
- Package names should be:
- Short
- Lowercase
- Single words
- Descriptive
- No Underscores, camelCase, PascalCase etc
package http
package json
package user
package authInitialisms#
- Common initialisms should remain fully capitalized.
- Examples of common initialisms:
- API, ASCII, CPU, CSS, DNS, EOF, GUID, HTML, HTTP, HTTPS, ID, IP, JSON, LHS, QPS, RAM, RHS, RPC, SLA, SMTP, SQL, SSH, TCP, TLS, TTL, UDP, UI, UID, UUID, URI, URL, UTF8, VM, XML, XSRF, XSS etc.
userID
httpServer
parseJSON
apiClient
userUUIDConstructor Naming Practices#
- No concept of constructors in golang, Instead constructors follow a naming convention:
New<TYPE>.
NewUser
NewClient
NewServerInterface Naming Practices#
- Interfaces often end with -er when they describe behaviours.
- These names describe
what the type does,NOT what it is.
Reader
Writer
Closer
Stringer
LoggerVariable Naming Practices#
- Variable names should be:
- Short
- Clear
- Contextual
count
user
totalPriceReceiver Naming Practices#
- Receiver variable names should be short and concise, usually one or two letters.
- Receiver names should usually be consistent across methods.
func (u *User) save() {}
func (c *Client) serve() {}
func (s *Server) Listen() {}Constant Naming Practices#
- Constants follow the same MixedCaps convention.
// Variable Connections
MaxConnections
DefaultTimeout
// Group Constants
StatusActive
StatusInactiveError Naming Practices#
- Error variables typically start with Err.
ErrUserNotFound
ErrInvalidToken
ErrConnectionClosedTests Naming Practices#
- Test functions must follow the format: TestXxx
TestUserCreation
TestCalculateTotal- Benchmark tests follow: BenchmarkXxx
BenchmarkParseJSON
BenchmarkDatabaseInsertFile Naming Practices#
- Go files typically use lowercase with underscores when necessary.
// Source Files
user.go
user_service.go
http_server.go
json_parser.go
// Test files
user_test.go
auth_test.goOthers#
- Avoid Redundant Naming
// Package: http
// Type: Server
http.Server // Good use
HTTPServer // Bad use- Getters Methods don’t prefix
Get, Instead direct use the function name. - Setter Methods do prefix Set.
// Getter Example
Name()
Age()
Balance()
// Setter Example
SetName()
SetBalance()