for loops maintain the same block on iteration, which is referenced in any closures generated within
title might be confusing, but here's the example:
package main
func main() {
var fns []func()
for _, v := range []int{1, 2, 3} {
x := v*100 + v
fns = append(fns, func() { println(x) })
}
for _, fn := range fns {
fn()
}
}
(the x := declaration is used to demonstrate that this does not reference v, whereby the behaviour talked about here would actually be correct in the current go specification, though this is due to change in go1.22)
go behaviour (expected):
101
202
303
gno behaviour:
303
303
303
I have a fix in #1585, it works like this:
package main
func main() {
var fns []func()
for _, v := range []int{1, 2, 3} {
x := v*100 + v
fns = append(fns, func() { println(x) })
}
for _, fn := range fns {
fn()
}
}
// Output:
// 101
// 202
// 303
Closures should perform late binding on captured variables.
The values should be resolved when the closure is executed, not when it is created.
For this to happen, we need to capture by *T and the value can be ad-hoc unwrapped so we keep the T semantics.
A new type representing this should be created, which should looks something like
//Upvalue is a name for captured variables in Lua VM
type Upvalue struct {
val *PointerValue
}
@jaekwon
Example by @ltzmaxwell that currently doesn't work
package main
func main() {
var fns []func() int
for i := 0; i < 5; i++ {
x := i
f := func() int {
return x
}
fns = append(fns, f)
x += 1
}
for _, fn := range fns {
println(fn())
}
}
// Output:
// 0
// 1
// 2
// 3
// 4
the outcome should be 1,2,3,4,5, while now get 0,1,2,3,4.
Putting this here for reference. Here are the attempts to fix this that have not been merged: #1768, #1585, https://github.com/deelawn/gno/pull/3
This is the one currently in progress: https://github.com/gnolang/gno/pull/1780
Putting this here for reference. Here are the attempts to fix this that have not been merged: #1768, #1585, deelawn#3
This is the one currently in progress: #1780
the latest attempt: #1818. #1780 has been proved not suitable for all scenarios.
@ltzmaxwell do we close #1818 or do you want to iterate on it?
@ltzmaxwell do we close #1818 or do you want to iterate on it?
it's actually ready for review. thanks.
close this as solved by #2429. Go1.22 loopvar is not supported at the moment, defer for future optimization. cc: @moul @thehowl @jaekwon for visibility.