0
0
Goprogramming~5 mins

Why defer is used in Go

Choose your learning style9 modes available
Introduction

Defer is used to delay a function call until the surrounding function finishes. It helps clean up resources like files or locks automatically.

Closing a file after reading or writing to it.
Releasing a lock after finishing a critical section.
Closing a network connection when done.
Undoing temporary changes before a function ends.
Ensuring cleanup code runs even if an error happens.
Syntax
Go
defer functionName(arguments)

The deferred function runs after the current function returns.

You can defer multiple calls; they run in last-in, first-out order.

Examples
This prints "Goodbye" after the current function ends.
Go
defer fmt.Println("Goodbye")
This opens a file and defers closing it until the function finishes.
Go
file, _ := os.Open("file.txt")
defer file.Close()
Sample Program

This program shows how defer delays the "Middle" print until after "End" prints.

Go
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Start")
	defer fmt.Println("Middle")
	fmt.Println("End")
}
OutputSuccess
Important Notes

Deferred calls run even if the function panics or returns early.

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

Summary

Defer delays a function call until the surrounding function ends.

It helps manage resources by ensuring cleanup code runs.

Deferred calls run in reverse order of their defer statements.