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