std.algorithm for changing array values
bearophile
bearophileHUGS at lycos.com
Wed Jan 15 16:07:56 PST 2014
Kapps:
> One thing to keep in mind is that structs are passed by value,
> so this foreach would be operating on a copy of the entry. So
> your setting the value to 42 would have no effect.
>
> Instead you would need "foreach(ref entry; entries)" in order to
> have the change take effect (regardless of whether or not you
> use std.algorithm).
This is a common bug in D code, especially in code of D newbies,
but it's also occasionally present in the code of more seasoned D
programmers.
One solution to avoid it that I suggested is that on default
foreach yields const values. So if you want to mutate the value
you have to add a "mutable" or "ref":
foreach (mutable entry; entries) {
Another language solution is to iterate by reference on default,
so the ref is implicit:
foreach (entry; entries) {
And if you want to iterate by value you need to write something
different.
There are other solutions. But none of them were accepted by
Walter :-(
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list