What is the preferred method for testing the existence of a key in an associative array?

Namespace rswhite4 at googlemail.com
Sat Sep 14 04:47:19 PDT 2013


On Saturday, 14 September 2013 at 11:32:23 UTC, simendsjo wrote:
> On Saturday, 14 September 2013 at 10:50:17 UTC, Jacob Carlborg 
> wrote:
>> On 2013-09-13 16:17, Orvid King wrote:
>>
>>> Well, I usually do it as:
>>>
>>> int[string] someCache;
>>>
>>> int getValue(string key)
>>> {
>>>    if (auto val = key in someCache)
>>>        return *val;
>>>    return someCache[key] = -3;
>>> }
>>
>> That doesn't work with generic code. I mean, -3 can be a legal 
>> value. There are many types that doesn't have an invalid 
>> value, like pointers do.
>
> I don't understand. What doesn't work? If the key exists, val 
> !is null, if it doesn't, val is null.

I guess, he means your default value -3 isn't appropriate for all 
types.


More information about the Digitalmars-d-learn mailing list