Changing behavior of associative array

Kevin Bailey keraba at yahoo.com
Sat Dec 16 20:04:54 UTC 2023


Perhaps someone can help solve this mystery. I have a sample 
program that adds structs to an associative array (as keys) in a 
subroutine. The program passes the array by reference as expected 
(below).

My real program does the same thing and yet the associative array 
is passed by value. Thus anything added in the subroutine is lost.

I've added a TON of writeln's to confirm this. The *instant* I 
made the parameter "ref", the real program starts acting as 
expected, and the print-outs show the correct results.

Does anyone know why the behavior would change? Has anyone seen 
anything like this?

I even tried importing the same libraries into both programs. The 
only remaining difference is that the real function has several 
more arguments (7), but I would be shocked if D changed its 
behavior because of that.

thx
```
import std.stdio;

struct Foo
{
     uint a, b, c;
}

void add_one_and_recurse(
     uint[Foo] m,
     int x)
{
     if (!x)
         return;
     foreach (k,v; m)         // Prints the 1 from main()
         writeln(k, ", ", v); // as expected.
     add_one_and_recurse(m, x-1);
     Foo f = {4, 5, x};
     m[f] = 7;
}

int main()
{
     uint[Foo] m;
     Foo f = {1, 2, 3};
     m[f] = 1;
     add_one_and_recurse(m, 3);
     foreach (k,v; m)         // Prints 4 items
         writeln(k, ", ", v); // as expected.
     return 0;
}
```



More information about the Digitalmars-d-learn mailing list