www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Associative Array Question

reply Chris Bare <chris bareflix.com> writes:
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);
Dec 31 2020
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
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
Dec 31 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Jan 01 2021