Go Comments
Document your Go code effectively
💬 Go Comments
Comments in Go help document your code, making it readable and maintainable. Go supports single-line and multi-line comments, plus special documentation comments for generating automatic documentation.
// This is a single-line comment
package main
/* This is a
multi-line comment */
import "fmt"
func main() {
fmt.Println("Comments make code clear!") // Inline comment
}
Output:
Comments make code clear!
Types of Comments
Single-line
Use // for one line comments
// This is a comment
name := "Alice"
Multi-line
Use /* */ for multiple lines
/* This comment
spans multiple
lines */
Documentation
Special comments for docs
// Package main demonstrates comments
package main
Inline
Comments at end of lines
age := 25 // User's age
🔹 Single-line Comments
Use
//
for single-line comments:
package main
import "fmt"
func main() {
// This is a single-line comment
fmt.Println("Hello, World!")
// You can have multiple single-line comments
// Each line needs its own // prefix
name := "Go Developer"
fmt.Println("Welcome,", name) // Inline comment here
// Comments can explain complex logic
result := calculateTax(1000, 0.08) // 8% tax rate
fmt.Printf("Tax: $%.2f\n", result)
}
// Function to calculate tax
func calculateTax(amount, rate float64) float64 {
return amount * rate // Simple multiplication
}
Output:
Hello, World!
Welcome, Go Developer
Tax: $80.00
🔹 Multi-line Comments
Use
/* */
for multi-line comments:
package main
import "fmt"
/*
This is a multi-line comment.
It can span several lines and is useful
for longer explanations or temporarily
disabling blocks of code.
*/
func main() {
/*
Multi-line comments are great for:
- Detailed explanations
- Temporarily disabling code
- License headers
- Complex algorithm descriptions
*/
fmt.Println("Multi-line comments demo")
/*
Uncomment this block to see more output:
fmt.Println("This line is commented out")
fmt.Println("So is this one")
*/
calculateArea(5, 10)
}
/*
calculateArea computes the area of a rectangle
Parameters:
- width: the width of the rectangle
- height: the height of the rectangle
Returns: prints the calculated area
*/
func calculateArea(width, height int) {
area := width * height
fmt.Printf("Area of %dx%d rectangle: %d\n", width, height, area)
}
Output:
Multi-line comments demo
Area of 5x10 rectangle: 50
🔹 Documentation Comments
Go has special conventions for documentation comments:
Documentation Rules:
-
Use
//(not/* */) for documentation - Start with the name being documented
- Place directly before the declaration
- Use complete sentences
// Package calculator provides basic math operations.
// It demonstrates proper Go documentation style.
package main
import "fmt"
// PI represents the mathematical constant π (pi).
const PI = 3.14159
// User represents a person using our application.
// It contains basic information about the user.
type User struct {
Name string // User's full name
Age int // User's age in years
}
// Add takes two integers and returns their sum.
// This function demonstrates basic arithmetic operations.
func Add(a, b int) int {
return a + b
}
// Greet creates a personalized greeting message.
// It takes a User struct and returns a formatted string.
func (u User) Greet() string {
return fmt.Sprintf("Hello, I'm %s and I'm %d years old!", u.Name, u.Age)
}
func main() {
// Create a new user
user := User{
Name: "Alice",
Age: 28,
}
// Display user greeting
fmt.Println(user.Greet())
// Perform calculation
result := Add(10, 15)
fmt.Printf("10 + 15 = %d\n", result)
// Use constant
fmt.Printf("PI value: %.5f\n", PI)
}
Output:
Hello, I'm Alice and I'm 28 years old!
10 + 15 = 25
PI value: 3.14159
🔹 Best Practices
Follow these guidelines for effective commenting:
Good Comments
Explain WHY, not WHAT
// Retry 3 times to handle network issues
for i := 0; i < 3; i++ {
Avoid
Don't state the obvious
// Increment i by 1
i++ // Bad comment
Keep Updated
Update comments with code changes
// Updated: Now handles edge cases
func process(data []string) {
Be Clear
Write for other developers
// Convert temperature from Celsius to Fahrenheit
temp := celsius*9/5 + 32
🔹 Practical Example
Here's a well-commented Go program:
// Package main demonstrates a simple banking system
// with proper documentation and commenting practices.
package main
import (
"fmt"
"time"
)
// Account represents a bank account with basic operations.
type Account struct {
Owner string // Account owner's name
Balance float64 // Current account balance
}
// NewAccount creates a new account with zero balance.
// It takes the owner's name and returns an Account pointer.
func NewAccount(owner string) *Account {
return &Account{
Owner: owner,
Balance: 0.0, // Start with zero balance
}
}
// Deposit adds money to the account.
// It returns an error if the amount is negative.
func (a *Account) Deposit(amount float64) error {
if amount < 0 {
return fmt.Errorf("cannot deposit negative amount: %.2f", amount)
}
a.Balance += amount // Add to current balance
return nil
}
// GetStatement returns a formatted account statement.
func (a *Account) GetStatement() string {
// Format current date and time
now := time.Now().Format("2006-01-02 15:04:05")
return fmt.Sprintf(
"Account Statement - %s\nOwner: %s\nBalance: $%.2f",
now, a.Owner, a.Balance,
)
}
func main() {
// Create new account
account := NewAccount("John Doe")
// Make some deposits
account.Deposit(100.50) // Initial deposit
account.Deposit(25.75) // Second deposit
/*
Display account information
This shows the current state after deposits
*/
fmt.Println(account.GetStatement())
}
Output:
Account Statement - 2024-01-15 14:30:25
Owner: John Doe
Balance: $126.25