iTranslated by AI
Deep Dive into Go's defer Statement
$ go version
go version 1.12
This article is a translation of Go: How Does defer Statement Work?.
The defer statement is a convenient way to execute code before a function returns.
As shown below, the defer statement is implemented as a LIFO (last-in-first-out) stack.
In other words, a defer method (a function executed by a defer statement) defined later is executed first.
func main() {
defer func() {
println(`defer 1`)
}()
defer func() {
println(`defer 2`)
}()
}
defer 2 <- Last in, first to go out
defer 1
Let's take a look at the internal implementation and what happens with more complex code.
Internal Implementation
Go implements LIFO using a linked list. In fact, the _defer struct contains a link field that represents a link to the next _defer struct.
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 links to the previous defer method to be executed next.
func newdefer(siz int32) *_defer {
var d *_defer
gp := getg() // get the current goroutine
// ...
// deferred list is now attached to the new _defer struct
d.link = gp._defer
gp._defer = d // the new struct is now the first to be called
return d
}
defer methods are executed sequentially starting from the top of the stack.
func deferreturn(arg0 uintptr) {
gp := getg() // get the current goroutine
d:= gp._defer // copy the deferred function to a variable
if d == nil { // if there is not deferred func, just return
return
}
// ...
fn := d.fn // get the function to call
d.fn = nil // reset the function
gp._defer = d.link // attach the next one to the goroutine
freedefer(d) // freeing the _defer struc
jmpdefer(fn, uintptr(unsafe.Pointer(&arg0))) // call the func
}
// first deferred func
0x001d 00029 (main.go:6) MOVL $0, (SP)
0x0024 00036 (main.go:6) PCDATA $2, $1
0x0024 00036 (main.go:6) LEAQ "".main.func1·f(SB), AX
0x002b 00043 (main.go:6) PCDATA $2, $0
0x002b 00043 (main.go:6) MOVQ AX, 8(SP)
0x0030 00048 (main.go:6) CALL runtime.deferproc(SB)
0x0035 00053 (main.go:6) TESTL AX, AX
0x0037 00055 (main.go:6) JNE 117
// second deferred func
0x0039 00057 (main.go:10) MOVL $0, (SP)
0x0040 00064 (main.go:10) PCDATA $2, $1
0x0040 00064 (main.go:10) LEAQ "".main.func2·f(SB), AX
0x0047 00071 (main.go:10) PCDATA $2, $0
0x0047 00071 (main.go:10) MOVQ AX, 8(SP)
0x004c 00076 (main.go:10) CALL runtime.deferproc(SB)
0x0051 00081 (main.go:10) TESTL AX, AX
0x0053 00083 (main.go:10) JNE 101
// end of main func
0x0055 00085 (main.go:18) XCHGL AX, AX
0x0056 00086 (main.go:18) CALL runtime.deferreturn(SB)
0x005b 00091 (main.go:18) MOVQ 16(SP), BP
0x0060 00096 (main.go:18) ADDQ $24, SP
0x0064 00100 (main.go:18) RET
0x0065 00101 (main.go:10) XCHGL AX, AX
0x0066 00102 (main.go:10) CALL runtime.deferreturn(SB)
0x006b 00107 (main.go:10) MOVQ 16(SP), BP
0x0070 00112 (main.go:10) ADDQ $24, SP
0x0074 00116 (main.go:10) RET
deferproc is called for each defer statement. Internally, this calls the newdefer function mentioned earlier, which registers a new method as a defer method.
Then, when the main function completes, the defer methods are called one after another by the deferreturn function.
The _defer struct mentioned earlier also has a _panic *_panic field.
Let's use another example to see what role this plays.
Return Values of defer Methods
The only way to access the return value of a defer method is by using named return values.
If the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned.
This can be hard to understand, so let's look at an example.
func main() {
fmt.Printf("with named param, x: %d\\n", namedParam())
fmt.Printf("without named param, x: %d\\n", notNamedParam())
}
func namedParam() (x int) {
x = 1
defer func() { x = 2 }()
return x
}
func notNamedParam() (int) {
x := 1
defer func() { x = 2 }()
return x
}
$ go run main.go
with named param, x: 2
without named param, x: 1
Knowing this behavior helps to understand the recover function even better. For more details, see this article.
The _defer struct has a _panic field. This field is set during a panic.
func gopanic(e interface{}) {
[...]
var p _panic
[...]
d := gp._defer // current attached defer on the goroutine
[...]
d._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
[...]
}
In fact, gopanic is called if a panic occurs before calling the defer method.
0x0067 00103 (main.go:21) CALL runtime.gopanic(SB)
0x006c 00108 (main.go:21) UNDEF
0x006e 00110 (main.go:16) XCHGL AX, AX
0x006f 00111 (main.go:16) CALL runtime.deferreturn(SB)
Let's see an example of a function that uses a named return value to recover from a panic.
func main() {
fmt.Printf("error from err1: %v\n", err1())
fmt.Printf("error from err2: %v\n", err2())
}
func err1() error {
var err error
defer func() {
if r := recover(); r != nil {
err = errors.New("recovered")
}
}()
panic(`foo`)
return err
}
func err2() (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New("recovered")
}
}()
panic(`foo`)
return err
}
error from err1: <nil>
error from err2: recovered
In err2, since err is a named return value, the assignment err = errors.New("recovered") is reflected.
By combining both, you can make the recover function and the error you want to return to the caller work correctly together.
Performance Improvements
In Go 1.8, the performance of defer was improved.
I tried comparing benchmarks before the improvement (1.7) and after (1.8).
name old time/op new time/op delta
Defer-4 99.0ns ± 9% 52.4ns ± 5% -47.04% (p=0.000 n=9+10)
Defer10-4 90.6ns ±13% 45.0ns ± 3% -50.37% (p=0.000 n=10+10)
It's nearly 50% faster!
For those who want to know more about the details of the improvement, refer to this link.
defer statements without arguments, where no memory copying occurs, have also been optimized.
Here is the benchmark for executing defer statements without arguments.
name old time/op new time/op delta
Defer-4 51.3ns ± 3% 45.8ns ± 1% -10.72% (p=0.000 n=10+10)
This is also about 10% faster.
Discussion