defer, Anonymous Functions & Closures
Deferred calls and function values
defer: Deferred Execution
defer schedules a function call to run when the surrounding function returns — regardless of how it returns (normal, error, panic):
func readFile(path string) {
f, err := os.Open(path)
if err != nil { return }
defer f.Close() // runs when readFile returns
// read from f...
}defer Evaluation Order
Deferred calls are pushed onto a stack and executed in LIFO order (last-in, first-out):
func main() {
defer fmt.Println("third")
defer fmt.Println("second")
defer fmt.Println("first")
// Output: first, second, third
}All lessons in this course
- Function Basics and Signatures
- Multiple Return Values
- Variadic Functions
- defer, Anonymous Functions & Closures