Foreach allows a less error-prone and better readable way to iterate collections. The attribute ref
can be used if we want to directly modify the iterated element.
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (ref el; arr)
{
el *= 2;
}
writeln(arr); // [2, 6, 8]
}
The index of the iteration can be accessed too:
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (i, el; arr)
{
arr[i] = el * 2;
}
writeln(arr); // [2, 6, 8]
}
Iteration in reverse order is possible too:
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
int i = 0;
foreach_reverse (ref el; arr)
{
el += i++; // 4 is incremented by 0, 3 by 1, and 1 by 2
}
writeln(arr); // [3, 4, 4]
}