capypad
0 day streak
go / beginner
Snippet

Defer: Scheduling Function Calls

The defer keyword schedules a function call to be executed after the surrounding function returns, but before the function actually exits. This is commonly used for cleanup tasks like closing files or releasing resources. Multiple defer statements execute in LIFO (Last In, First Out) order - the last defer statement runs first when the function returns.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
 
import "fmt"
 
func main() {
fmt.Println("Start")
 
defer fmt.Println("Deferred 1")
defer fmt.Println("Deferred 2")
defer fmt.Println("Deferred 3")
 
fmt.Println("Middle")
 
fmt.Println("End")
}
Breakdown
1
defer fmt.Println("Deferred 1")
Schedules this call to run after main returns
2
defer fmt.Println("Deferred 2")
Second defer, will run before Deferred 1
3
defer fmt.Println("Deferred 3")
Third defer, will run before Deferred 2
4
Output order:
Start, Middle, End, Deferred 3, Deferred 2, Deferred 1