Skip to content

Instantly share code, notes, and snippets.

@betandr
Last active February 5, 2019 17:04
Show Gist options
  • Save betandr/64c4df4747581dea5d18dd37579c91de to your computer and use it in GitHub Desktop.
Save betandr/64c4df4747581dea5d18dd37579c91de to your computer and use it in GitHub Desktop.
Capturing iteration variables with Go
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