Skip to content

Instantly share code, notes, and snippets.

@dacr
Created March 28, 2025 09:02
Show Gist options
  • Save dacr/d2c4201c247fbd5f9645ea6baebb3878 to your computer and use it in GitHub Desktop.
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/9b1ace202d31481f00aa83be33a1bef5bc1c9369
/*?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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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