defer is a language feature in Go and Zig. In Golang, such a statement defers the execution of an expression (including a function call) until the surrounding function returns. In Zig, it defers its execution to the end of a block/scope. With multiple defer calls, they are executed in LIFO order.

defer is prototypically used to clean-up resources after they are acquired/created. For instance:

  • After a file has been opened, we can defer its closure, i.e., defer f.Close()
  • We can unlock a mutex after it’s been acquired, i.e., defer mu.Unlock()
  • We can also defer a closure.

In this sense, defer functions much like RAII does in object-oriented languages, in that they function to close/destruct an object’s resources upon the end of a scope.