Naming Conventions
Golang has established naming conventions that help developers write clean, consistent, and readable code. Understanding and following these conventions is essential for creating high-quality software.
Variable Naming Conventions
Camel Case for Variables
Use camelCase for local variables and function parameters:
var userAge int
var firstName string
func calculateTotal(itemPrice float64) float64 {
// Function implementation
}
Short and Meaningful Names
Prefer concise names that clearly describe the purpose:
// Good example
var count int
var userList []User
// Avoid overly verbose names
var numberOfItemsInTheShoppingCart int // Too long
Package and Type Naming
Package Names
- Use lowercase
- Be concise and descriptive
- Reflect the package's purpose
package database
package usermanagement
Type Naming
Use PascalCase for types and interfaces:
type User struct {
Name string
Age int
}
type Validator interface {
Validate() bool
}
Function Naming Conventions
graph TD
A[Function Naming] --> B[Use camelCase]
A --> C[Be descriptive]
A --> D[Start with verb]
A --> E[Reflect action or behavior]
Examples of good function names:
func validateUser(user User) bool
func calculateDiscount(price float64) float64
func connectToDatabase() error
Constant and Enum Naming
Constants
Use UPPER_SNAKE_CASE for constants:
const MAX_USERS = 100
const DATABASE_TIMEOUT = 30
Enum-like Constants
type UserRole int
const (
RoleAdmin UserRole = iota
RoleUser
RoleGuest
)
Naming Conventions Table
Category |
Convention |
Example |
Variables |
camelCase |
userAge |
Constants |
UPPER_SNAKE_CASE |
MAX_CONNECTIONS |
Types |
PascalCase |
UserProfile |
Interfaces |
PascalCase |
Validator |
Packages |
lowercase |
database |
Common Anti-Patterns
Avoid these naming mistakes:
// Bad examples
var x int // Non-descriptive
var USER_NAME string // Incorrect case
func DoSomething() // Unnecessary capitalization
Recommendations
- Be consistent across your project
- Choose names that reveal intent
- Avoid abbreviations
- Keep names short but meaningful
LabEx encourages developers to internalize these naming conventions to write more professional and maintainable Golang code.