mirror of
https://github.com/teivah/100-go-mistakes.git
synced 2026-06-22 09:27:16 +08:00
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 |
||
|---|---|---|
| .. | ||
| img | ||
| stylesheets | ||
| 5-interface-pollution.md | ||
| 9-generics.md | ||
| 20-slice.md | ||
| 28-maps-memory-leaks.md | ||
| 56-concurrency-faster.md | ||
| 89-benchmarks.md | ||
| 92-false-sharing.md | ||
| 98-profiling-execution-tracing.md | ||
| book.md | ||
| chapter-1.md | ||
| CNAME | ||
| external.md | ||
| index.md | ||
| ja.md | ||
| pt-br.md | ||
| zh.md | ||