Associative Array, get value instead of poiter using `if (auto ..)`, possible?

evilrat evilrat666 at gmail.com
Sun Sep 1 09:45:05 UTC 2024


On Sunday, 1 September 2024 at 08:50:53 UTC, ryuukk_ wrote:
>
> if checking for/getting a value from a hashmap requires all 
> that crap, then perhaps something is wrong with the language, 
> and it perhaps isn't the one i should have picked for the task
>
> my mistake perhaps, not yours
>
>
> besides, i do use the language features in my project, 
> templates and mixins to solve larger problems, it's great, and 
> reason why i picked D
>


An alternative would be yet another template wrapper for get 
value that takes a dictionary an a lambda and call that lambda 
only if value is present, this means you no longer do the if, but 
rather a "cryptic" call like in some other languages.

pseudo code:
```d
// helper function
void withKey(V,K,L)(V[K] dict, K key, lazy L dostuff) {
     if (auto value = dict.get(K)) {
         doStuff(*value);
     }
}

// usage

string[int] counters;
counters["foo"] = 42;
counters.withKey("foo", (value) {
     assert(value == 42);
});
```


More information about the Digitalmars-d-learn mailing list