dmd icon indicating copy to clipboard operation
dmd copied to clipboard

AAs should require pass-by-reference for `update`

Open Bolpat opened this issue 1 month ago • 0 comments

The update function for associative arrays takes as its third parameter an update callback which can have two forms: One that returns the new value to be associated with the key and one that updates the value in place (passing it by reference).

The second variant allows passing the associated value by copy, but this is a conceptually bug.

int[int] aa = [1: 10];
aa.update(1, () => 10, delegate void(int x) { ++x; });

The above code compiles and runs, although it does not update the value. The programmer clearly intended delegate void(ref int x) { ++x; });. And even in the fringe case where the value is intentionally just observed and not actually updated, passing by reference is no harm.

That should be an error, and it would be if in the constraint for update function it was ensured that in case is(typeof(update(aa[K.init])) == void)) also something like [__traits(getParameterStorageClasses, update(aa[K.init]), 0)] == ["ref"] is true. Requiring ref alone is a bit harsh as e.g. scope ref is no harm.

Bolpat avatar Dec 02 '25 18:12 Bolpat