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?

Reply via email to