congdong007

Penetration Test、Software Developer

0%

defer in the Go Language

In Go language, defer is a very useful keyword used for deferring the execution of functions, typically employed for performing cleanup or resource release operations before a function returns.

A defer statement pushes the function call that should be deferred onto a stack and executes these deferred function calls in a last-in, first-out (LIFO) order just before the current function returns.

Here are some important features and uses of defer:

  1. Deferred Execution: Using the defer keyword ensures that a function call is executed before the containing function returns, whether it returns normally or due to an error.

  2. Resource Cleanup: Common use cases include closing files, releasing locks, closing database connections, and other cleanup operations to prevent resource leaks.

  3. Parameter Evaluation: The parameters in a defer statement are evaluated when the defer statement is executed, not when the function returns.

Here are some examples demonstrating the use of defer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import "fmt"

func main() {
// Example 1: defer for file closing
file := openFile("example.txt")
defer closeFile(file)

// Example 2: defer for logging function execution time
defer logTime("Function execution")

// Example 3: Multiple defer statements execute in a last-in, first-out order
for i := 1; i <= 5; i++ {
defer fmt.Println("Deferred statement", i)
}

fmt.Println("Function body")
}

func openFile(filename string) *File {
fmt.Println("Opening file:", filename)
return // Open the file and return the file handle
}

func closeFile(file *File) {
fmt.Println("Closing file")
// Close the file
}

func logTime(message string) {
fmt.Println(message, "at some time")
}

In the above examples, defer statements are used to ensure the file is closed before main returns, log the execution time of the function, and execute multiple defer statements in a last-in, first-out order.

defer is a powerful tool in Go that can help you write safer and cleaner code, ensuring proper resource release and consistency.”