DEV Community

Cover image for Go Programming Language: Everything You Need To Know About It (Part 9)
Ganesh Kumar
Ganesh Kumar

Posted on

Go Programming Language: Everything You Need To Know About It (Part 9)

#go

Hello, I'm Ganesh Kumar. I'm working on git-lrc: a Git hook for Checking AI generated code.
AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.
git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

In my previous post, We learned about conditional control flow.

Now we will learn about defer.

Why defer is used?

The primary purpose of defer is to ensure that certain tasks are performed regardless of how a function exits (whether it completes successfully, reaches a return statement, or even "panics" due to an error).

  • Reliability: It prevents resource leaks (like leaving a file open) by allowing you to pair "open" and "close" actions together visually in the code.
  • Panic Safety: Even if the program throws an error (a "panic") in the middle of a function, deferred functions are still executed by the Go runtime before the program crashes.
  • Readability: It keeps the cleanup logic near the initialization logic, making the code easier to follow.

Where defer is used?

It is commonly used in scenarios where you must "clean up" after an operation:

  • Closing Files: After opening a file for reading or writing, you immediately defer the Close() call so you don't forget it at the end of the function.
  file, err := os.Open("file.txt")
  if err != nil {
      return err
  }
  defer file.Close()
Enter fullscreen mode Exit fullscreen mode
  • Database Connections: When you establish a connection or a transaction, you defer the disconnection or rollback to ensure the connection is returned to the pool.
// 1. Get a connection/transaction from the database
tx, err := db.Begin()
    if err != nil {
        return err
    }

    // 2. IMMEDIATELY defer the Rollback.
    // If the function returns early (due to an error), the transaction is cancelled.
    // If the transaction was already Committed, Rollback does nothing.
    defer tx.Rollback()
Enter fullscreen mode Exit fullscreen mode
  • Unlocking Mutexes: If you lock a mutex for thread safety, you defer the Unlock() call to ensure other parts of your program can access the resource later.
// 1. Lock the Mutex (Take the key)
    s.mu.Lock()

    // 2. IMMEDIATELY defer the Unlock (Ensure the key is returned)
    defer s.mu.Unlock()
Enter fullscreen mode Exit fullscreen mode
  • Tearing Down Tests: In unit testing, it is used to clean up temporary databases or files created specifically for the test.

Key Behavior (The Stack)

If you use multiple defer statements in one function, Go pushes them onto a stack. This means they are executed in Last-In, First-Out (LIFO) orderβ€”the last thing you deferred will be the first thing to run when the function exits.

Example: If you defer "World" then defer "Hello", the output when the function ends will be "Hello World".

package main

import (
    "fmt"
)

func main() {

    defer fmt.Println("World")
    fmt.Println("Hello")
}

Enter fullscreen mode Exit fullscreen mode
gk@jarvis:~/exp/code/rd/go-exmaple$ go run main.go
Hello
World
Enter fullscreen mode Exit fullscreen mode

Here this is what happens step-by-step:

  1. defer fmt.Println("World") is executed. Go schedules fmt.Println("World") to run when main() exits. It doesn't print anything yet.
  2. fmt.Println("Hello") runs immediately and prints "Hello".
  3. The main() function finishes its work and is about to return.
  4. The deferred function fmt.Println("World") is executed, printing "World".

Conclusion

With this we understood about defer in go. where it is used and how it is used.

git-lrc

πŸ‘‰ Check out: git-lrc
Any feedback or contributors are welcome! It’s online, open-source, and ready for anyone to use.
⭐ Star it on GitHub:

GitHub logo HexmosTech / git-lrc

Free, Unlimited AI Code Reviews That Run on Commit

git-lrc logo

git-lrc

Free, Unlimited AI Code Reviews That Run on Commit


git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • πŸ€– AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • πŸ” Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.
  • πŸ” Build a habit, ship better code. Regular review β†’ fewer bugs β†’ more robust code β†’ better results in your team.
  • πŸ”— Why git? Git is universal. Every editor, every IDE, every AI…




Top comments (0)