Struct immutable data and dict

Alex sascha.orlov at gmail.com
Tue Sep 4 11:25:15 UTC 2018


On Tuesday, 4 September 2018 at 10:30:24 UTC, Timoses wrote:
>
> However, of course this also fails because randomly assigning 
> the array elements will overwrite it. So the associative array 
> seems like the better idea. However, not being able to 
> INITIALIZE an assoc array element disallows its usage.
>
> Is there any solution, trick or workaround??

If the initialization of assoc array is not the matter, but the 
initialization of an element of it, then, the question is rather:
"Is the absence of an immutable value in an assoc array worth to 
be garanteed, because the values are immutable?" Isn't it?

No idea about this :p

´´´
void main()
{
	import std.stdio;
	auto r = Range("dummy");
	r.fun(3).writeln;
}

struct Res
{
	immutable int i;
}

struct Range
{
	this(string)
	{
		c = [0 : Res(42), 5: Res(73), /*3: Res(4)*/];
	}

	Res[size_t] c;

	Res fun(size_t i)
	{
		if (auto p = i in c)
			return *p;
		else
		{
			//c[3] = Res(3);   /// ERROR line 26
			return Res(int.max);
		}
	}
}
´´´

I tried two workarounds:
1) let the immutable away.
2) preallocate a full array of immutables. Then, misuse the assoc 
array by using the keys only. If the key is there, then, yield 
the appropriate element from the preallocated array. If not, 
yield the "elephant in Cairo".


More information about the Digitalmars-d-learn mailing list