Last active
February 5, 2019 17:04
-
-
Save betandr/64c4df4747581dea5d18dd37579c91de to your computer and use it in GitHub Desktop.
Capturing iteration variables with Go
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" | |
func main() { | |
tempDirs := []string{"one", "two", "three", "four", "five"} | |
var rmdirs []func() | |
for _, dir := range tempDirs { | |
// Without this `dir := dir` line rmdir func would use outer `dir` | |
// which is a reference that has been updated in successive loops so | |
// accesses the last item repeatedly. With this line it uses the shadow | |
// value correctly. | |
dir := dir | |
rmdirs = append(rmdirs, func() { | |
fmt.Println(dir) | |
}) | |
} | |
// ... | |
for _, rmdir := range rmdirs { | |
rmdir() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment