mirror of
https://github.com/teivah/100-go-mistakes.git
synced 2026-06-22 01:17:11 +08:00
📖 100 Go Mistakes and How to Avoid Them
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 |
||
|---|---|---|
| .cache/plugin/social | ||
| .github | ||
| docs | ||
| includes | ||
| overrides | ||
| site | ||
| src | ||
| .gitattributes | ||
| .gitignore | ||
| CONTRIBUTING.md | ||
| go.mod | ||
| go.sum | ||
| justfile | ||
| LICENSE.md | ||
| mkdocs.yml | ||
| README.md | ||