Sobes.tech
Senior

In what order are multiple defer statements executed in a single function?

sobes.tech AI

Answer from AI

In Go, multiple defer calls within a single function are executed in LIFO (Last In, First Out) order — meaning the last deferred call will be executed first upon exiting the function.

Example:

func example() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    defer fmt.Println("Third")
}
// When exiting example(), the output will be:
// Third
// Second
// First