0
0
Goprogramming~5 mins

Defer execution order in Go

Choose your learning style9 modes available
Introduction

Defer lets you delay running a piece of code until the surrounding function finishes. It helps clean up resources in the right order.

Closing a file after reading or writing
Unlocking a mutex after locking it
Releasing a network connection after use
Printing a message after a function ends
Cleaning up temporary resources in reverse order
Syntax
Go
defer functionCall()

Deferred calls run just before the function returns.

If you defer multiple calls, they run in last-in, first-out order.

Examples
This prints "Third" first, then "Second", then "First" because deferred calls run in reverse order.
Go
defer fmt.Println("First")
defer fmt.Println("Second")
fmt.Println("Third")
This defers closing the file until the function ends, ensuring the file is always closed.
Go
file, _ := os.Open("file.txt")
defer file.Close()
Sample Program

This program shows that deferred calls run after the main function finishes, in reverse order of defer statements.

Go
package main

import "fmt"

func main() {
    defer fmt.Println("First deferred")
    defer fmt.Println("Second deferred")
    fmt.Println("Function body")
}
OutputSuccess
Important Notes

Deferred functions run even if the function panics.

Arguments to deferred functions are evaluated immediately, but the call happens later.

Summary

Use defer to delay code until a function ends.

Deferred calls run in reverse order.

Great for cleanup tasks like closing files or unlocking.