Search⌘ K
AI Features

The defer Keyword

Explore how the defer keyword works in Go to delay function calls until the surrounding function returns. Understand its LIFO execution order and how using defer with anonymous functions can cause bugs. Learn best practices for clear and safe defer usage in your Go code.

So far, we have seen defer in previous lessons, as well as in the implementations of the phone book application. But what does defer do? The defer keyword postpones the execution of a function until the surrounding function returns. Usually, defer is used in file I/O operations to keep the function call that closes an opened file close to the call that opened it. This helps to avoid the common programmer error where we forget to close a file—that we had opened earlier—just before the function exits.

Deferred functions

It is very important to remember that deferred functions are executed in last in, first out (LIFO) order after the surrounding function has been returned. Putting it simply, this means that if we defer function f1() first, function f2() second, and function f3() third in ...