Naming convention in go
Go is a young language. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives.
In Go, naming conventions for variables, functions, and types follow a consistent pattern to improve readability and maintainability. Here are the key conventions:
Package Naming Conventions
- Use all
lowercase. - Avoid underscores (_).
- Keep package names short and meaningful.
- Use singular form, except in cases like bytes, strings.
Examples:
package auth // Good
package userutils // Bad (too long)
Variable Naming Conventions
- Use short but descriptive names.
- Avoid underscores (_).
- Use camelCase (first word's first letter small and other word's first letter capital) for local variables & unexported package-level variables.
- Use PascalCase (word's first letter capital) for exported package-level variables.
(It's not convention, it a rule)
Use acronyms in uppercase (HTTPResponse, not HttpResponse).
Examples:
package main import "fmt" var globalVar = "I am global" // Package-level variable var OfficeName = "Learnsic" // can be exported (PascalCase) func main() { userName := "Rasbin" // Local variable (camelCase) fmt.Println(userName) }
Constant Naming Conventions
- Use
UPPER_CASEwith underscores for global constants. - Use
camelCasefor local constants. Prefix boolean constants with is, has, or should. Eg: isUpdated, hasSubmitted.
Examples:
const MAX_USERS = 100 // Global constant func main() { const minAge = 18 // Local constant fmt.Println(minAge) }
Function Naming Conventions
- Make the function name descriptive and start with a verb.
- Use
camelCasefor unexported functions (private). Use
PascalCasefor exported functions (public).(It's not convention, it a rule)
Examples:// Exported function (Public) func PrintMessage(msg string) { fmt.Println(msg) } // Unexported function (Private) func calculateSum(a, b int) int { return a + b }
Type Naming Conventions
- Use
PascalCasefor type names (structs, interfaces, etc.). - Use singular nouns for struct names.
Interface names should describe behavior and end with
-erif appropriate.Examples:
// Struct (PascalCase) type User struct { Name string Email string } // Interface (ending with `-er` convention) type Writer interface { Write(data string) error }
Receiver Naming in Methods
- Use short, meaningful receiver names.
- Use a single letter if it's clear (u for User, c for Config).
Use this or self only in rare cases.
Example:type User struct { Name string } // Method with receiver `u` func (u User) GetName() string { return u.Name }
Leave a comment
1 Comment
thank you for this. <3