Created
March 31, 2016 11:09
-
-
Save keshavab/b87b506d548f476855909b4613cdcdd2 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 functions() []func() { | |
// pitfall of using loop variables | |
arr := []int{1, 2, 3, 4} | |
result := make([]func(), 0) | |
// functions are not evaluated, functions definitions are returned | |
// since functions refer to i, arr[i] | |
// the last values of i, arr[i] are always referred to | |
for i := range arr { | |
result = append(result, func() { fmt.Printf("index - %d, value - %d\n", i, arr[i]) }) | |
} | |
// if desired behaviour is needed, one needs to use them as args | |
//for i := range arr { | |
// result = append(result, func(index, val int) { fmt.Printf("index - %d, value - %d\n", index, val) }) | |
//} | |
return result | |
} | |
func main() { | |
fns := functions() | |
for f := range fns { | |
fns[f]() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment