Defer in Go
Go: Defer
In Go, the keyword "defer" is used to schedule a function call to be executed after the surrounding function returns.
Syntax for defer in Go
The basic syntax for defer is:
defer functionCall(arguments)
- When a function is called with the
defer
keyword, it is not executed immediately. - Instead, it is added to a stack of deferred function calls. When the surrounding function returns, the deferred function calls are executed in last-in-first-out order.
- This means that the function call that was deferred last will be executed first, followed by the second-to-last deferred call, and so on.
Here's an example of how defer can be used to ensure that a file is closed after it has been opened:
func readMyFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
// Read from file and return data
...
}
- In this example, the
os.Open
function is called to open the file with the given filename. - If the file cannot be opened, an error is returned. Otherwise, the
f.Close()
call is deferred using the defer keyword. - This ensures that the file will be closed after the
readMyFile
function returns, even if an error occurs during the reading of the file.
Defer can be used to ensure that resources are freed up, connections are closed, or any other cleanup work is done after a function has finished executing.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go