Associative array literal is non-constant?

Artur Skawina art.08.09 at gmail.com
Sat Feb 4 06:41:04 PST 2012


On 02/04/12 07:46, H. S. Teoh wrote:
> On Fri, Feb 03, 2012 at 10:18:18PM -0800, H. S. Teoh wrote:
>> Why does the following code give a compiler error?
>>
>> 	static int[string] table = ["abc":1, "def":2, "ghi":3];
>>
>> Error message is:
>>
>> 	prog.d:3: Error: non-constant expression ["abc":1,"def":2,"ghi":3]
>>
>> How is a literal non-constant?
> [...]
> 
> Ugh. Just found this:
> 
> 	http://d.puremagic.com/issues/show_bug.cgi?id=6238
> 
> Further testing shows that assoc array literals can't be used outside of
> function scope at all, for example:
> 
> 	// (in package scope)
> 	auto hash = [ "abc":1, "def":2, "ghi":3 ];
> 		// Error: non-constant expression ["abc":1,"def":2,"ghi":3]
> 
> Seems like a pretty nasty bug to me.

Consider the implementation, ie what you have to do to make const AAs work...

I think I'd prefer them to be distinct types, that do not implicitly convert
to the non-const variant. Then the compiler is free to implement them 
differently, eg by picking a perfect hash, ensuring there are no collisions etc.
This would let you use them for fast local lookups, which is probably what
most use cases of const AAs are. And if you assign it to another AA, the new
one is initialized at runtime from the values in the const AA. Which (runtime
init) is the only way possible currently. It shouldn't happen implicitly
because for larger arrays the conversion could be expensive.

Defining a non-const AA initialized from a literal (like in the quoted examples
above) is the non-obvious case. If nothing modifies the array and it does not
leave the scope everything's fine. But if one of these things happens, doing
the init/conversion at runtime might not be what the user expects. So keeping
mutable AAs initialized from literals illegal would probably be the best thing.

Note: AA literals are documented to be non-const [1], so all of the above would
be backwards compatible - it only allows for things which currently are illegal.

artur

[1] Somewhere on dlang.org. Can't find that page right now.


More information about the Digitalmars-d-learn mailing list