Created
March 31, 2016 10:50
-
-
Save keshavab/6657265a36ec1748ee0ea1fe71b7e91f to your computer and use it in GitHub Desktop.
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
package main | |
import "fmt" | |
func counter(start int) (func() int, func()) { | |
// if the value gets mutated, the same is reflected in closure | |
ctr := func() int { | |
return start | |
} | |
incr := func() { | |
start++ | |
} | |
// both ctr and incr have same reference to start | |
// closures are created, but are not called | |
return ctr, incr | |
} | |
func main() { | |
// ctr, incr and ctr1, incr1 are different | |
ctr, incr := counter(100) | |
ctr1, incr1 := counter(100) | |
fmt.Println("counter - ", ctr()) | |
fmt.Println("counter1 - ", ctr1()) | |
// incr by 1 | |
incr() | |
fmt.Println("counter - ", ctr()) | |
fmt.Println("counter1- ", ctr1()) | |
// incr1 by 2 | |
incr1() | |
incr1() | |
fmt.Println("counter - ", ctr()) | |
fmt.Println("counter1- ", ctr1()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment