Defer

By deferring a function, it will run whenever the current function is exited. This is a convenient way to ensure that a function will get executed before exiting, which is useful for cleaning up or closing files. It is convenient because a deferred function will get executed no matter where the surrounding function exits if there are multiple return locations.

Common use cases are deferring calls to close a file or database connection. Right after opening a file, you can defer a call to close. This will ensure that a file is closed whenever the function is exited, even if there are multiple return statements and you can't be sure about when and where the current function will exit.

This example demonstrates a simple use case for the ...

Get Security with Go 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.