Defer Keyword in Golang


Golang is a statically-typed programming language that is popular among developers for its simplicity, concurrency support, and garbage collection. One of the unique features of Golang is the defer keyword, which is used to schedule a function call to be executed after the function completes. In this article, we will explore the defer keyword in Golang, its syntax, and use cases.

What is the Defer Keyword?

In Golang, the defer keyword is used to delay the execution of a function until the surrounding function completes. The deferred function calls are executed in Last-In-First-Out (LIFO) order. That means the most recently deferred function is executed first, followed by the second most recently deferred function, and so on.

The defer keyword is useful when we want to ensure that certain operations are performed before a function returns, regardless of whether an error occurs or not. This can help simplify error handling and make code more readable.

Syntax of the Defer Keyword

The syntax of the defer keyword is straightforward. We simply use the keyword followed by the function call we want to defer. Here's an example −

Example

package main

import "fmt"

func main() {
   defer fmt.Println("World")

   fmt.Println("Hello")
}

In this example, the function fmt.Println("World") is deferred until after the main function completes. As a result, the output of this program is −

Output

Hello
World

The deferred function is executed after the main function completes, resulting in the output "World" being printed to the console.

Multiple Deferred Function Calls

In Golang, we can defer multiple function calls in a single function. When we defer multiple functions, they are executed in reverse order. Here's an example −

Example

package main
import "fmt"
func main() {
   defer fmt.Println("Third")
   defer fmt.Println("Second")
   defer fmt.Println("First")
   fmt.Println("Hello")
}

In this example, we defer three different function calls, and they are executed in reverse order. As a result, the output of this program is −

Output

Hello
First
Second
Third

Deferred Functions and Panics

The defer keyword is particularly useful in cases where we want to recover from a panic. A panic is an error that occurs at runtime when a program cannot continue executing. When a panic occurs, the program is terminated and an error message is printed to the console.

By using the defer keyword, we can ensure that certain cleanup functions are executed even in the event of a panic. Here's an example −

Example

package main

func main() {
   defer cleanup()

   // Perform some operations that may cause a panic
}

func cleanup() {
   if r := recover(); r != nil {
      // Log the error
   }

   // Clean up resources
}

In this example, we defer the cleanup function at the beginning of the main function. If a panic occurs during the execution of the main function, the cleanup function is still executed before the program terminates. This can help ensure that resources are properly cleaned up and that any necessary error logging occurs.

Conclusion

The defer keyword in Golang is a powerful tool that can simplify error handling and ensure that certain operations are always performed before a function returns. By using the defer keyword, we can ensure that cleanup functions are executed, even in the event of a panic. This can help make code more robust and improve the overall reliability of our programs.

Updated on: 07-Apr-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements