Sobes.tech
Junior

What concept is implemented using the defer construct in Go?

sobes.tech AI

Answer from AI

The defer construct implements the concept of deferred function execution. The deferred function is executed immediately before the containing function finishes.

Key points:

  • Execution time: The deferred function executes at the very end of the parent function, even if a panic or exception occurs.
  • Stack: Deferred calls form a stack. The last deferred call will be executed first (LIFO).
  • Variable capture: Arguments of the deferred function are evaluated at the moment of defer declaration, not at execution time.

Examples of typical usage:

  • Closing files, network connections, mutexes.
  • Restoring state (e.g., after changing global variables or flags).
  • Measuring execution time.
// Example of using defer to close a file
func readFile(filename string) error {
	f, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer f.Close() // The file will be closed before exiting the function

	// Reading from the file...
	return nil
}
// Example of a defer stack
func process() {
	defer fmt.Println("First from the stack")
	defer fmt.Println("Second from the stack")
	defer fmt.Println("Third from the stack") // Will execute last

	fmt.Println("Processing...")
}

Deferred calls with arguments:

// Example of capturing variable value at defer declaration time
func demonstrateDeferArgEval() {
	i := 0
	defer fmt.Println("Value of i in defer:", i) // i will be 0

	i++
	fmt.Println("Value of i after increment:", i) // i will be 1
}