0Pricing
Go Academy · Lesson

defer, Anonymous Functions & Closures

Deferred calls and function values

defer, Anonymous Functions & Closures is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
}

defer for Cleanup

defer is the idiomatic way to ensure resources are released:

  • Unlock a mutex after locking it
  • Close a file after opening it
  • Commit or rollback a database transaction
  • Call WaitGroup.Done() after WaitGroup.Add()

defer with Arguments

The arguments to a deferred call are evaluated immediately when defer is called, not when it executes:

x := 10
defer fmt.Println(x) // prints 10, not 20
x = 20
fmt.Println(x)       // prints 20

Anonymous Functions

Anonymous functions (function literals) are defined inline without a name:

double := func(n int) int {
    return n * 2
}
fmt.Println(double(5)) // 10

// Immediately invoked:
result := func(a, b int) int { return a + b }(3, 4)

Closures

A closure is a function that captures variables from its surrounding scope:

func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

ctr := makeCounter()
fmt.Println(ctr(), ctr(), ctr()) // 1 2 3

Closure Capture Gotcha in Loops

Closures capture variables by reference — a common goroutine loop bug:

for i := 0; i < 3; i++ {
    i := i // create a new variable per iteration
    go func() { fmt.Println(i) }()
}

defer with Named Returns

Deferred functions can modify named return values — useful for annotating errors:

func doWork() (err error) {
    defer func() {
        if err != nil {
            err = fmt.Errorf("doWork: %w", err)
        }
    }()
    return riskyOp()
}

Functional Patterns with Closures

Closures enable functional patterns like memoization:

func memoize(f func(int) int) func(int) int {
    cache := map[int]int{}
    return func(n int) int {
        if v, ok := cache[n]; ok {
            return v
        }
        v := f(n)
        cache[n] = v
        return v
    }
}

Closures as Middleware

Closures are the building block for middleware in Go HTTP servers — they wrap a handler and add behavior around it:

func withLogging(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        log.Printf("%s %s", r.Method, r.URL)
        next(w, r)
    }
}

Quick Check

When are the arguments to a deferred function call evaluated?

Recap: defer, Closures & Anonymous Functions

These features make Go code expressive and safe:

  • defer guarantees cleanup at function exit — LIFO order
  • Arguments to defer are evaluated immediately
  • Anonymous functions can be assigned to variables or called inline
  • Closures capture surrounding variables by reference
  • Watch for loop variable capture bugs in goroutines

Next course: Arrays, Slices & Maps.

Frequently asked questions

Is the “defer, Anonymous Functions & Closures” lesson free?

Yes — the full text of “defer, Anonymous Functions & Closures” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “defer, Anonymous Functions & Closures”?

Deferred calls and function values You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “defer, Anonymous Functions & Closures” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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