Hacker News new | ask | show | jobs
by WalterBright 14 days ago
D has several usages for `foreach` depending on the number and type of its arguments. In this case, it sees that `vec` is an array, and so constructs a loop over the array. If `vec` was a range, the loop will be constructed as a loop over the array.

It's nice because it makes the syntax for arrays and ranges interchangeable, making for easy refactoring.

1 comments

Go is similar: `for/range` has always worked on arrays, slices, maps, strings and channels, and they extended it to integers in version 1.22 and to user-defined generators in version 1.23. It generates one or two outputs depending on the type of the RHS, but one can assign the index value to _ to ignore it. Among standard types, only channels and integers generate one output; containers (including strings) give an index or key and a value.