Become a Golang Pro with 10 “Defer” Tricks

Go’s defer keyword is a powerful tool that allows you to specify a function call to be executed later, usually after the surrounding function has returned. Although it may seem like a simple concept, the defer keyword can be used in several advanced ways to improve the efficiency and reliability of your Go code.

This post will explore ten advanced tricks for using delay in Go. From canceling events and releasing resources to printing the time a function uses and recovering from panics, these techniques will help you take your Go skills to the next level. Whether you’re a beginner who wants to learn more about defer, or an experienced developer looking to expand their knowledge, this post has something for you.

  1. Defer a function call to execute after the surrounding function returns:
func main() {
defer fmt.Println("This will be printed after main returns")
}

2. Defer a function call to execute in the reverse order they were deferred:

func main() {
defer fmt.Println("This will be printed last")
defer fmt.Println("This will be printed second")
defer fmt.Println("This will be printed first")
}

3. Defer a function call to execute even if a panic occurs:

func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()

// This will cause a panic
a := []int{1, 2, 3}
fmt.Println(a[3])
}

4. Defer a function call to close a file:

func main() {
file, err := os.Open("test.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()

// Do something with the file
}

5. Defer a function call to unlock a mutex: