Strange closure behaviour
Emmanuelle
VuLXn6DBW at PPtUm7TvV6nsw.com
Sat Jun 15 00:24:52 UTC 2019
Take a look at this code:
---
import std.stdio;
void main()
{
alias Func = void delegate(int);
int[][] nums = new int[][5];
Func[] funcs;
foreach (x; 0 .. 5) {
funcs ~= (int i) { nums[x] ~= i; };
}
foreach (i, func; funcs) {
func(cast(int) i);
}
writeln(nums);
}
---
(https://run.dlang.io/is/oMjNRL)
The output is:
---
[[], [], [], [], [0, 1, 2, 3, 4]]
---
Personally, this makes no sense to me. This is the result I was
expecting:
---
[[0], [1], [2], [3], [4]]
---
Why is it "locking" the bound `x` to the last element? It seems
like the compiler is overwriting the closure for `x`, somehow.
So, I'm wondering why D is doing that. Is it a compiler bug? Or
is this the expected behaviour?
More information about the Digitalmars-d-learn
mailing list