WeCodeAcademy

Go Closures and defer

A closure is a function that remembers the variables around it. defer runs a call when the surrounding function ends, which is perfect for cleanup.

ExampleGo
package main

import "fmt"

func counter() func() int {
  n := 0
  return func() int {
    n++
    return n
  }
}

func work() {
  defer fmt.Println("cleanup runs last")
  defer fmt.Println("deferred calls run in reverse order")
  fmt.Println("working")
}

func main() {
  next := counter()
  fmt.Println(next(), next(), next())
  other := counter()
  fmt.Println(other())
  work()
}
Output
1 2 3
1
working
deferred calls run in reverse order
cleanup runs last
Quick check

When does a deferred call run?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.