Is there any relation between for-range and closures in Go? I think that for-range can be thought of as using a closure.
A possible answer could be this code that has the same behavior. Firstly, I use a closure and secondly, I use a for-range loop.
package main
import "fmt"
func main() {
names := [4]string{"John", "Marie", "David", "Alex"}
iter := generator(names)
for true {
i, v := iter()
fmt.Printf("%v %s
", i, v)
if i == 3 {
break
}
}
fmt.Println("---------------------------------")
for i, v := range names {
fmt.Printf("%v %s
", i, v)
}
}
func generator(arr [4]string) func() (int, string) {
index := 0
return func() (int, string) {
nextName := arr[index]
index++
return index - 1, nextName
}
}
Is there any relation between for-range and closures in Go?
No.
(The only thing to remember is that the loop variables are reused on each iteration an closures inside the for loop will all close over the same variable. See https://golang.org/doc/faq#closures_and_goroutines)