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:
Philipp Stehle 2024-08-12 22:30:16 +02:00 committed by GitHub
parent 1074108bce
commit f807004a97
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1099,8 +1099,8 @@ Theres 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