The defer Keyword

Let’s learn what the defer keyword does.

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 the same surrounding function, then when the surrounding function is about to return, function f3() will be executed first, function f2() will be executed second, and function f1() will be the last one to get executed.

Coding example

In this lesson, we will discuss the dangers of defer when used carelessly using a simple program. The code for defer.go is as follows:

Get hands-on with 1200+ tech skills courses.