Last active
February 3, 2026 20:19
-
-
Save dacr/d2c4201c247fbd5f9645ea6baebb3878 to your computer and use it in GitHub Desktop.
go defer trap / published by https://github.com/dacr/code-examples-manager #613fc74b-18b9-4df3-a193-a8752921526c/10188c3b5470f735fbe140bce957db66b901d74f
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/ | |
| // summary : go defer trap | |
| // keywords : go, defer, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 613fc74b-18b9-4df3-a193-a8752921526c | |
| // created-on : 2025-03-27T10:06:35+01:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : nix-shell -p go --run "go run $file" | |
| package main | |
| import "fmt" | |
| func main() { | |
| div1, div2 := 10, 5 | |
| defer divide(div1, div2) // values copied | |
| defer func() { divide(div1, div2) }() // Closure capture !! here | |
| defer func(myDiv1, myDiv2 int) { divide(myDiv1, myDiv2) }(div1, div2) // values copied | |
| div1, div2 = 17, 5 | |
| // defered are executed in reverse way, LIFO | |
| } | |
| func divide(dividend, divisor int) { | |
| fmt.Printf("%v - %v\n", dividend/divisor, dividend%divisor) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment