[Issue 17526] Add a set method for AA

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sun Jul 9 07:07:11 PDT 2017


https://issues.dlang.org/show_bug.cgi?id=17526

--- Comment #6 from Bolpat <qs.il.paperinik at gmail.com> ---
@Vladimir Exactly. It's a performance and possibility issue. We can discuss the
name after everything else is done.
I propose a change to the signature + semantics:

  V* set(K, V)(ref const(V)[const(K)] aa, auto ref const(K) key, lazy const(V)
value)
  {
    if (auto valPtr = key in aa) return null;
    // cast away const as initialization is okay:
    (cast() aa[key]) = value();
    return key in aa;
  }

So it returns null if it was not set and a pointer to the object in the AA to
be able to modify it after setting without additional lookups. I like addOrGet
very much. Both methods have their range of applicability. With this one, you
can do

  if (auto valPtr = aa.set(key, val()))
  {
    valPtr.property = something();
    manage(*valPtr);
  }

The main difference between the two is what you intend to do:
  - Yours assures the key has a value afterwards. It doesn't really care if the
key is there already. One cannot even know using it.
  - Mine expects the key not to be there beforehand. It is specifically
designed to add this key-value pair.

--


More information about the Digitalmars-d-bugs mailing list