The defer keyword

The defer keyword postpones the execution of a function until the surrounding function returns, which is widely used in file input and output operations because it saves you from having to remember when to close an opened file. The defer keyword allows you to put the function call that closes an opened file near to the function call that opened it. As you will learn about the use of defer in file-related operations in Chapter 8, Telling a UNIX System What to Do, this section will present two different usages of defer. You will also see defer in action in the section that talks about the panic() and recover() built-in Go functions, as well as in the section that is related to logging.

It is very important to remember that ...

Get Mastering Go - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.