AA and struct with const member

Stanislav Blinov stanislav.blinov at gmail.com
Wed Dec 29 04:20:21 UTC 2021


On Wednesday, 29 December 2021 at 02:33:08 UTC, frame wrote:
> On Wednesday, 29 December 2021 at 01:11:13 UTC, Stanislav 
> Blinov wrote:
>
>> Because opIndexAssign cannot distinguish at compile time 
>> between initialization and assignment:
>>
>> ```d
>> Stuff[Key] aa;
>> aa[key] = Stuff(args); // ostensibly, initialization
>> aa[key] = otherStuff;  // assignment to existing value
>> ```
>>
>> Same syntax, different behavior. This can only be caught at 
>> runtime. `require` and `update` though should be able to pull 
>> this off, and that they don't is a bug.
>
> Of course but opIndexAssign() isn't there in my example. The 
> compiler should call runtime's _aaGetY() or something like that 
> directly.

It is doing that. You've asked why that should be compile error, 
and the answer is - because there's no way to distinguish between 
initialization and assignment here. I.e. you can't make one line 
compile and the other - not. Either both compile, or both don't. 
So if you allow them to compile, you'll have to have a runtime 
check, throwing an exception on attempt to assign. Which is just 
horrible. Better to leave the assignment a compile error, and 
make `require` and `update` do the job they're supposed to be 
doing.


More information about the Digitalmars-d-learn mailing list