Allocating an empty non null associative arary

Vladimir Panteleev thecybershadow.lists at gmail.com
Tue Mar 31 06:09:56 UTC 2020


On Tuesday, 31 March 2020 at 02:51:11 UTC, Superstar64 wrote:
> How do I generically create an empty associative array?

If you can't pass it by ref, then adding and then removing an 
element is the only way I know.

/// Ensure that arr is non-null if empty.
V[K] nonNull(K, V)(V[K] aa)
{
	if (aa !is null)
		return aa;
	aa[K.init] = V.init;
	aa.remove(K.init);
	assert(aa !is null);
	return aa;
}

unittest
{
	int[int] aa;
	assert(aa is null);
	aa = aa.nonNull;
	assert(aa !is null);
	assert(aa.length == 0);
}



More information about the Digitalmars-d-learn mailing list