Go Defer Function Call

1. Introduction

In Go, the defer statement is used to ensure that a function call is performed later in a program’s execution, typically for purposes of cleanup. defer is often used where e.g., ensure and finally would be used in other languages. This post will explain the defer statement in Go with an example.

Definition

The defer statement in Go postpones the execution of a function until the surrounding function returns, either normally or through a panic. Multiple defer statements call the deferred functions in the reverse order they were deferred.

2. Program Steps

1. Define a function that we want to execute last, using the defer statement.

2. Perform some other operations or function calls.

3. Observe how the deferred function executes after the surrounding function completes.

3. Code Program

package main

import "fmt"

func main() {
	// Open a resource
	fmt.Println("Opening a resource")

	// Defer the closing of the resource
	defer fmt.Println("Closing the resource")

	// Do operations with the resource
	fmt.Println("Performing an operation with the resource")
}

Output:

Opening a resource
Performing an operation with the resource
Closing the resource

Explanation:

1. package main - The program's package is defined as main.

2. import "fmt" - The fmt package is imported for formatted I/O.

3. In the main function, an example resource is "opened" by printing "Opening a resource".

4. The defer statement is then used with fmt.Println("Closing the resource"). This function call is deferred, which means it will be executed just before the main function returns.

5. Another print statement simulates doing some work with the resource.

6. After the main function completes its execution, the deferred fmt.Println("Closing the resource") call is executed.

7. The output shows that even though the defer statement was placed before the operation, the deferred function call is executed last.


Comments