0Pricing
Go Academy · Lesson

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

  1. Function Basics and Signatures
  2. Multiple Return Values
  3. Variadic Functions
  4. defer, Anonymous Functions & Closures
← Back to Go Academy