Defer statements

August 23, 2024

We’re at the last item in the “Statements” section of the spec, before we move on to built-in functions. And naturally, the last one is… the defer statement~

Defer statements

A “defer” statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

DeferStmt = "defer" Expression .

The expression must be a function or method call; it cannot be parenthesized. Calls of built-in functions are restricted as for expression statements.

So two points for today. Then we’ll talk about more details in the coming day or two.

  1. A defer statement looks a lot like a go statement. And in some ways, they are the same: Both go and defer continue immediately, without waiting for their corresponding function to execute. Both take a function invocation as an argument. Both ignore any return values from the function. So at a syntactic level, if you can write a go statement, you can write a defer statement. But other than these fairly superficial similarities, they’re completely different. 😂

  2. There’s one situation (well, two) where defer functions are not executed when a function terminates: When the program exits!

    This is one important reason to restrict your use of os.Exit (or other functions that call it—such as log.Fatal).

    There’s nothing worse than going to the effort to call defer logger.Close() to make sure your error logger flushes all errors to your cloud logging solution when the program exits, so that you can debug any problems, then you call log.Fatal, so that the program exits with an error, but doesn’t actually flush that buffer before it exits.

    And no. Of course I’ve never done that myself. It was, uhm… a friend.

Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe