Sobes.tech
Middle

In what order are deferred functions executed in Go?

sobes.tech AI

Answer from AI

Deferred functions are executed in the reverse order of their definition, i.e., LIFO (Last-In, First-Out).

package main

import "fmt"

func main() {
	defer fmt.Println("first") // Defined last
	defer fmt.Println("second") // Defined second last
	defer fmt.Println("third") // Defined first
}

As a result, the output of this code will be:

third
second
first

When exiting the scope (function) where a defer was declared, the deferred functions are called sequentially in reverse order. This is useful for releasing resources, closing files, unlocking mutexes, and other cleanup operations.