defer

A Go statement that schedules a function call to run when the surrounding function returns, used for cleanup such as closing a file.

In more detail

Write defer f.Close() on the line after a successful open, so the file is closed on every return path. Deferred calls run in reverse order and still run during a panic. They do not run when the program calls os.Exit.

Example

defer f.Close()

Related terms

Taught in

References