digitalmars.D.learn - Strange behavior using array of structures
Hi all,
I have:
```
import std.stdio;
void main() {
Logger[] log;
Logger l0 = Logger(0,1);
Logger l1 = Logger(100,1);
Logger l2 = Logger(200,1);
log ~= l0;
log ~= l1;
foreach (i; 0 .. 3) {
writeln("it:", i);
foreach (l; log) {
l.run;
}
}
}
struct Logger {
int initial;
int increment;
void run() {
initial += increment;
writeln("\t", initial);
}
}
```
Output:
```
it:0
1
101
it:1
1
101
it:2
1
101
```
If I use:
```
void main() {
Logger[] log;
Logger l0 = Logger(0,1);
Logger l1 = Logger(100,1);
Logger l2 = Logger(200,1);
log ~= l0;
log ~= l1;
foreach (i; 0 .. 3) {
writeln("it:", i);
l0.run();
l1.run();
}
}
```
output (correct) is:
```
it:0
1
101
it:1
2
102
it:2
3
103
```
can someone help me to understand? Thanks!
Apr 04 2018
On Wednesday, 4 April 2018 at 10:00:18 UTC, Orfeo wrote:
foreach (l; log) {
l.run;
}
Try making this "foreach (ref l; log) {".
Structs are value types in D, so by default they're copied when
you assign them to another variable (in this case l). That means
run() is modifying a copy that gets thrown away each time. "ref
l" makes l into a reference to the original struct instance.
Apr 04 2018
On Wednesday, 4 April 2018 at 10:09:41 UTC, sarn wrote:On Wednesday, 4 April 2018 at 10:00:18 UTC, Orfeo wrote:Great!! thank you very muchforeach (l; log) { l.run; }Try making this "foreach (ref l; log) {". Structs are value types in D, so by default they're copied when you assign them to another variable (in this case l). That means run() is modifying a copy that gets thrown away each time. "ref l" makes l into a reference to the original struct instance.
Apr 04 2018








Orfeo <orfeo.davia gmail.com>