On Sunday, 15 April 2018 at 22:52:47 UTC, Giles Bathgate wrote:
The function provides a means to get a value corresponding to the key, but if the value doesn't exist it will evaluate the lazy argument to create a new value, add this to the associative array and then return it.

auto p = lookup.getOrAdd("giles", new Person);

Thanks for making this pull, I've thought about solving this before. I think the function needs to provide a way to tell if the value was already present. I also think it's more ergonomic not to have to use a lazy argument, and probably more efficient, so I had in mind:

Value* slot(AA aa, K key, scope bool* inserted = null);

bool inserted;
auto p = aa.slot("key", &inserted);
if (inserted) {
  ...
  *p = new Value(...);
}
// use *p

This pattern needs a pointer to be returned, instead of using `ref`. Note that `&inserted` is valid in @safe code, but only with -dip1000. I called the function `slot` because it always returns the address of the slot which the value is stored in.

Reply via email to