mirror of
https://github.com/teivah/100-go-mistakes.git
synced 2026-06-22 01:17:11 +08:00
Update #47: change function call order in closure variant
As defer statements are evaluate in reverse order simply wrapping multiple defer in a closure reverses their call order. Sometimes this might be irrelevant, but as a general advise, I would recommend to swap it. See https://play.golang.com/p/NTtl-mHnx2x ```golang package main import ( "fmt" ) func main() { direct() closure() } func direct() { defer fmt.Println("direct a") defer fmt.Println("direct b") } func closure() { defer func() { fmt.Println("closure a") fmt.Println("closure b") }() } /* Output: direct b direct a closure a closure b */ ``` Another difference is behavior on `panic`: When adding two separate `defers` and one panics the other is still executed. This is not the case for a single defered closure. See https://play.golang.com/p/cMYJ7c3pVYJ
This commit is contained in:
parent
1074108bce
commit
f807004a97
1 changed files with 1 additions and 1 deletions
|
|
@ -1099,8 +1099,8 @@ There’s another solution: calling a closure (an anonymous function value that
|
|||
func f() error {
|
||||
var status string
|
||||
defer func() {
|
||||
notify(status)
|
||||
incrementCounter(status)
|
||||
notify(status)
|
||||
}()
|
||||
|
||||
// The rest of the function unchanged
|
||||
|
|
|
|||
Loading…
Reference in a new issue