Last active
August 29, 2015 14:18
-
-
Save johnclaus/3f8662487166d00ca252 to your computer and use it in GitHub Desktop.
Deferred closure execution within a loop
This file contains 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
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func increment(val *int) { | |
defer func() { | |
fmt.Println(time.Now(), ": Pre-increment: ", *val) | |
*val++ | |
fmt.Println(time.Now(), ": Post-increment: ", *val) | |
}() | |
} | |
func main() { | |
j := 1 | |
for i := 0; i < 4; i++ { | |
increment(&j) | |
} | |
fmt.Println(time.Now(), ": final j: ", j) | |
} | |
/* | |
============ | |
OUTPUT: | |
============ | |
$ go run deferral.go | |
2015-03-31 10:26:06.110453248 -0600 MDT : Pre-increment: 1 | |
2015-03-31 10:26:06.110682894 -0600 MDT : Post-increment: 2 | |
2015-03-31 10:26:06.110690739 -0600 MDT : Pre-increment: 2 | |
2015-03-31 10:26:06.110693545 -0600 MDT : Post-increment: 3 | |
2015-03-31 10:26:06.110695858 -0600 MDT : Pre-increment: 3 | |
2015-03-31 10:26:06.110698067 -0600 MDT : Post-increment: 4 | |
2015-03-31 10:26:06.110700312 -0600 MDT : Pre-increment: 4 | |
2015-03-31 10:26:06.110702463 -0600 MDT : Post-increment: 5 | |
2015-03-31 10:26:06.110704647 -0600 MDT : final j: 5 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment