Go - 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 defer Keyword

The syntax of the defer keyword is straightforward. We simply use the keyword followed by the function call we want to defer:

defer functionName(arguments)

Example

In this example, the deferred function is executed after the main function completes, resulting in the output "World" being printed to the console:

package main
import "fmt"
func main() {
   defer fmt.Println("World")
   fmt.Println("Hello")
}

As a result, the output of this program:

Hello
World

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.

Example

In this example, we defer three different function calls, and they are executed in reverse order.

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

Following is the ooutput to the above program:

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.

Example

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.

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
}
It will not generate anything, Just blank
Advertisements