Thread overview
Associative Array Question
Jan 01, 2021
Chris Bare
Jan 01, 2021
Adam D. Ruppe
January 01, 2021
I'm missing something about the way associative arrays are allocated.
In the example below, case 1 and case 2 seem to be the same, a type indexed by a long.
Case 2 fails with a Range violation.

Can someone explain the difference?
I found a work around (or the correct way) in case 3.

struct Project
{
	string  date;
	string  name;
}

		// case 1
		string[long] a1;
		a1[10] = "testing a1";

		foreach (f; a1)
			writeln ("name ", f);

		// case 2
		Project[long] a2;
		a2[10].name = "testing a2";

		foreach (f; a2)
			writeln ("name ", f.name);

		// case 3
		Project*[long] a3;
		a3[10] = new Project;
		a3[10].name = "testing a3";

		foreach (f; a3)
			writeln ("name ", f.name);
January 01, 2021
On Friday, 1 January 2021 at 01:43:50 UTC, Chris Bare wrote:
> 		a1[10] = "testing a1";

this actually constructs a new thing since it is a straight x = y assignment.

> 		a2[10].name = "testing a2";

But this looks up something first. It doesn't construct a2[10], it looks it up first to fetch the name member... hence the range violation since it isn't constructed yet.


> 		a3[10] = new Project;

and this again will construct since it is a straight x = y again.



So you could also do

a2[10] = Person()

then do the lookup of name
January 01, 2021
On 12/31/20 8:54 PM, Adam D. Ruppe wrote:
> On Friday, 1 January 2021 at 01:43:50 UTC, Chris Bare wrote:
>>         a1[10] = "testing a1";
> 
> this actually constructs a new thing since it is a straight x = y assignment.
> 
>>         a2[10].name = "testing a2";
> 
> But this looks up something first. It doesn't construct a2[10], it looks it up first to fetch the name member... hence the range violation since it isn't constructed yet.
> 
> 
>>         a3[10] = new Project;
> 
> and this again will construct since it is a straight x = y again.
> 
> 
> 
> So you could also do
> 
> a2[10] = Person()
> 
> then do the lookup of name

or a2[10] = Person(null, "testing a2")

-Steve