Closures/Value capture: Difference between revisions

 
Line 962:
func #3: 9
</pre>
 
You don't need to use this trick anymore in Go 1.22+:
{{works with|Go|1.22+}}
<syntaxhighlight lang="go">package main
 
import "fmt"
 
func main() {
fs := make([]func() int, 10)
for i := range fs {
fs[i] = func() int {
return i * i
}
}
fmt.Println("func #0:", fs[0]())
fmt.Println("func #3:", fs[3]())
}</syntaxhighlight>
{{out}}
<pre>
func #0: 0
func #3: 9
</pre>
If you take advantage of this, you should declare <pre>go 1.22</pre> in your go.mod file, so that older Go versions will not compile it. See [https://go.dev/blog/loopvar-preview this page] for more information.
 
=={{header|Groovy}}==
Solution: