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
- os.Open — The Go function that opens a file for reading and returns an *os.File you can stream from and must close.
- recover — The built-in Go function that, called inside a deferred function, stops a panic and returns the value it was raised with.
- panic — A Go run-time failure that stops normal execution, runs deferred functions and, unless recovered, crashes the program with a stack trace.
- os.Exit — The Go function that ends the program immediately with the exit code you give it, such as 0 for success.
Taught in
- Your First Program and go run — Concurrent Systems Programming with Go
- Panics and Recover — Concurrent Systems Programming with Go
- Goroutines and Concurrent Execution — Concurrent Systems Programming with Go
- Context Cancellation and Timeouts — Concurrent Systems Programming with Go
- Files and the os Package — Concurrent Systems Programming with Go
- Parsing Arguments with flag — Concurrent Systems Programming with Go
- Graceful Shutdown on SIGTERM — Concurrent Systems Programming with Go
- Executing Concurrent Checks — Concurrent Systems Programming with Go