getting rid of immutable (or const)

ag0aep6g anonymous at
Thu Sep 5 20:10:03 UTC 2019

On 05.09.19 21:51, berni wrote:
>> void main()
>> {
>>     int[int] a;
>>     immutable int b = 17;
>>     a[1] = b;                          // <-- expecting error here
>>     const oldPointer = (1 in a);
>>     immutable int c = 10;
>>     a[1] = c;
>>     assert(oldPointer is (1 in a));
>>     Point[int] d;
>>     immutable Point e = Point(17);
>>     d[1] = e;                           // <-- but error is here
>> }
>> struct Point
>> {
>>     immutable int x;
>> }
> What's the difference? I can put an immutable int in an AA and I can 
> overwrite it (pointer is still the same),

You're not putting an immutable int into an AA. You're copying the value 
of an immutable int to a mutable one.

> but I can't do that with a 
> struct, having an immutable member. When I remove that immutable inside 
> of the struct it works. ?!?

`Point` is effectively the same as `immutable long`. A better simile 
would be this: `immutable(int)[int] a; a[1] = 17;`. And now you get the 
same error. You can't overwrite the element, because its immutable.

You could argue that there is no element before assigning (initializing) 
`d[1]` for the first time. So the assignment should go through the first 
time, and it should only be an error when you try to write a second 
time. But figuring that out mechanically is hard, and DMD isn't smart 
enough to do it. So, to be on the safe side, it just says that you can't 
do that at all.

More information about the Digitalmars-d-learn mailing list