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.
-
A
defer
statement looks a lot like ago
statement. And in some ways, they are the same: Bothgo
anddefer
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 ago
statement, you can write adefer
statement. But other than these fairly superficial similarities, they’re completely different. 😂 -
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 aslog.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 calllog.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)