go / beginner
Snippet
Defer: Delayed Execution in Go
The defer keyword schedules a function call to run immediately after the surrounding function returns. This is perfect for cleanup tasks like closing files or releasing resources. Deferred functions execute in Last-In-First-Out order, meaning the last defer added runs first when the function exits.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package mainimport "fmt"func main() {defer fmt.Println("World")fmt.Println("Hello")}func readFile(name string) {file := "open""defer fmt.Println("Closing:", file)fmt.Println("Reading:", name)file = "close"}
Breakdown
1
defer fmt.Println("World")
Schedules fmt.Println to run after main() completes, but before it returns
2
fmt.Println("Hello")
Executes immediately, then deferred print runs after
3
defer fmt.Println("Closing:", file)
Captures current value of file variable for deferred execution
4
file = "close"
Variable changes, but deferred call already captured the original value