When are associative arrays meant to throw a RangeError?

Ben Davis entheh at cantab.net
Sat Feb 18 13:42:46 PST 2012

On 18/02/2012 20:54, Andrej Mitrovic wrote:
> Returning the default initializer of the value type when the key
> doesn't exist is a bad idea. Consider an integer, it's .init value is
> 0. If I want to check if a value of a key is zero I could easily end
> up with a silent bug:
> int[string] aa;
> aa["foobar"] = 5;
> if (aa["fobar"] == 0) { }  // will always be true
> else { }

Isn't this the kind of situation where you should be using an enum for 
the key type? Or indeed just creating a struct or a class to hold the 
values you need? Especially as remove() already gives you 'silent bugs' 
if the key is misspelled.

More information about the Digitalmars-d mailing list