Go: How Does defer Statement Work?
ℹ️ This article is based on Go 1.12.
defer
statement is a convenient way to execute a piece of code before a function returns, as explained in Golang specification:
Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
Here is an example of the LIFO (last-in-first-out) implementation:
func main() {
defer func() {
println(`defer 1`)
}()
defer func() {
println(`defer 2`)
}()
}defer 2 <- Last in, first to go out
defer 1
Let’s have a look at the internals and then a more complex case.
Internals implementation
Go runtime implements the LIFO with a linked list. Indeed, a defer struct has a link to the next one to be executed:
type _defer struct {
siz int32
started bool
sp uintptr
pc uintptr
fn *funcval
_panic *_panic
link *_defer // next deferred function to be executed
}
When a new defer method is created, it is attached to the current Goroutine and the previous one is linked to the new one as the next function to be executed:
func newdefer(siz int32) *_defer {
var d…