D isn't the only language with janky closure semantics

Timon Gehr timon.gehr at gmx.ch
Sat Aug 30 13:21:12 UTC 2025


On 8/30/25 12:18, ltdk wrote:
> On Friday, 29 August 2025 at 22:28:17 UTC, H. S. Teoh wrote:
> 
>>
>> Now, JS is certainly not a model language to follow, but it's 
>> interesting how it shares with D the same issue over closures 
>> involving loop variables.
>>
>> I guess that means we're not alone. :-P  Even though this situation is 
>> definitely not ideal.
>>
>>
>> T
> 
> Pior to 1.22, Golang also behaves similarly. They later "fixed" the 
> issue: https://go.dev/blog/loopvar-preview .
> 
> C# also moved away from Dlang's behavior since C# 5, 1 member of C# team 
> commented about that change: https://github.com/golang/go/ 
> discussions/56010#discussioncomment-3788526

These are _not_ "Dlang's behavior". They did not corrupt memory, D does.

D closures are much more broken than this simple usability problem.

What you are talking about is essentially the difference between a lowering:

```
foreach(i;0..n){ ... } -> for(int i=0;i<n;i++){ ... }
```
and
```
foreach(i;0..n){ ...} -> for(int _i=0;_i<n;_i++){ int i=_i; ... }
```
The other languages basically moved from the first variant to the second 
one.

It's a somewhat subtle point because there are many simple cases where 
using the first lowering behaves similarly to using the second lowering 
in D.

D is just broken here, it actually already uses the second lowering and 
it still does not work properly.

Of course, this should be fixed, because it has the same usability 
problem that the other languages fixed and is even unsound, causing more 
usability problems on top of that.


More information about the Digitalmars-d mailing list