Populating nested AAs; "This wouldn't be so verbose in Ada 2020"

Paul Backus snarwin at gmail.com
Sun Dec 8 06:42:22 UTC 2019


On Sunday, 8 December 2019 at 04:17:45 UTC, mipri wrote:
> Hello,
>
> I've got this code:
>
>   struct UserStats {
>     int ok, evil;
>   }
>
>   // module-level variable
>   UserStats[string][string] userHistory;
>
> and this code that populates it:
>
>   // loop over DB query
>
>   if (host !in userHistory)
>       userHistory[host] = typeof(userHistory[host]).init;
>
>   if (user !in userHistory[host])
>       userHistory[host][user] = 
> typeof(userHistory[host][user]).init;
>
>   if (ok) ++userHistory[host][user].ok;
>   else ++userHistory[host][user].evil;

You can use the `require` function [1] for this:

with (userHistory.require(host).require(user)) {
     if (isOk) ++ok; // renamed to avoid shadowing
     else ++evil;
}

Many "methods" for built-in AAs are located in the `object` 
module. It makes them a bit tricky to find in the documentation, 
if you don't already know they're there.

https://dlang.org/phobos/object.html#.require


More information about the Digitalmars-d-learn mailing list