πŸš€ Common Go Errors and How to Avoid Them

Learn to identify and fix the most frequent mistakes in Golang.

This article covers the most frequent mistakes developers make in Go (Golang) and provides best practices to avoid them. Each mistake is explained with a problem scenario, incorrect implementation, and a correct solution.

1️⃣ Forgetting to Handle Errors Properly

One of the common mistakes in Go is the lack of error handling. It is important to always check for errors when working with potentially faulty values. Use the error type to verify if an error has occurred and handle it appropriately.

❌ Common Mistake: Ignoring error handling can lead to crashes!
For example :
file, _ := os.Open("nonexistent.txt") // ❌ Ignoring error
fmt.Println(file.Name()) // ❌ May cause a panic!
❌ Common Mistake: Using panic instead of proper error handling.
For example :
panic(errors.New("something went wrong")) // ❌ Bad practice

βœ… Best Practices

βœ… Solution: Always check and handle errors properly.
For example :
file, err := os.Open("nonexistent.txt")
if err != nil {
    fmt.Println("Error:", err) // βœ… Proper error handling
    return
}
βœ… Solution: Use structured error handling.
For example :
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero") // βœ… Return meaningful error
    }
    return a / b, nil
}
βœ… Solution: Leverage errors.Is for better error handling.
For example :
if errors.Is(err, ErrPermissionDenied) {
    fmt.Println("Access denied.") // βœ… Handling specific error
}

2️⃣ Not Using `defer` to Release Resources

❌ Problem: Forgetting to release resources can cause memory leaks.

One of the most common mistakes in Go is forgetting to release resources such as files, network connections, or database queries after using them. This can lead to memory leaks, resource exhaustion, or unexpected behavior in your program.

πŸ“Œ What is defer in Go?

defer is a built-in keyword in Go that postpones the execution of a function until the surrounding function returns. It is commonly used to ensure that resources are properly released when a function completes.

❌ Problem: Forgetting to Close Resources

❌ Issue: If an error occurs before closing, the file remains open.
For example:
func openFile() {
    file, err := os.Open("data.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    file.WriteString("Hello, Go!") // ❌ File might remain open
}

βœ… Solution: Use defer to Ensure Closure

βœ… Fix: Ensures that the file is closed properly.
For example:
func openFile() {
    file, err := os.Open("data.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close() // βœ… Ensures closure
    file.WriteString("Hello, Go!")
}

πŸ“Œ Other Use Cases for defer

1️⃣ Closing Database Connections

For example:
func queryDatabase() {
    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close() // βœ… Ensures database connection is closed properly
}

2️⃣ Unlocking a Mutex in Concurrent Code

For example:
var mu sync.Mutex
func safeIncrement() {
    mu.Lock()
    defer mu.Unlock() // βœ… Ensures the mutex is unlocked even if an error occurs
    // Critical section
}

3️⃣ Flushing Buffers (e.g., HTTP Response Writers)

For example:
func sendResponse(w http.ResponseWriter) {
    w.Write([]byte("Processing request..."))
    defer w.Write([]byte("Response completed.")) // βœ… Ensures this message is always written
}

⚠️ When NOT to Use defer

While defer is useful, there are cases where you should avoid it for performance reasons:

1️⃣ Inside Loops – If used inside a loop, defer statements accumulate, causing performance issues.

For example:
for i := 0; i < 1000; i++ {
    file, _ := os.Open("file.txt")
    defer file.Close() // ❌ BAD: This will create 1000 deferred function calls!
}

βœ… Better Alternative: Close the file immediately within the loop.

For example:
for i := 0; i < 1000; i++ {
    file, _ := os.Open("file.txt")
    file.Close() // βœ… Close it immediately after usage
}
➑️ Read more

πŸš€ Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! β˜•πŸ˜Š

πŸ’» I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! πŸ™Œ


β˜• Buy me a coffee