From f807004a97169f19113206cc0bc47516d43c9275 Mon Sep 17 00:00:00 2001 From: Philipp Stehle Date: Mon, 12 Aug 2024 22:30:16 +0200 Subject: [PATCH] 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 --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 859532d..728d17d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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