TIL
capturing iteration variables in Go
- 1 minutes read - 152 wordsI was going through The Go Programming Language and in chapter 5 there was a section Caveat: Capturing Iteration Variables
.
The example is like this:
var rmdirs []func()
for _, dir := range tempDirs() { // 1
os.MkdirAll(dir, 0755) // 2
rmdirs = append(rmdirs, func() {
os.RemoveAll(dir) // NOTE: incorrect! // 3
})
}
dir
is the same variable. i.e. the address of the variable is samedir
’s value evaluated at this point is different at each iteration- IMPORTANT
dir
is not evaluated here. Its just being used. It will be evaluated only when thefunc()
is called
The following explanation from Ref[1]:
var rmdirs []func()
tempDirs := []string{"one", "two", "three", "four"}
for _, d := range tempDirs {
dir := d
fmt.Printf("dir=%v, *dir=%p\n", dir, &dir)
rmdirs = append(rmdirs, func() {
fmt.Printf("dir=%v, *dir=%p\n", dir, &dir)
})
}
fmt.Println("---")
for _, f := range rmdirs {
f()
}
Reference: 1. https://stackoverflow.com/questions/52980172/cannot-understand-5-6-1-caveat-capturing-iteration-variables 2. https://github.com/golang/go/wiki/CommonMistakes