head const (again), but for free?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Wed Jan 13 20:26:37 UTC 2021


On Wednesday, 13 January 2021 at 19:52:16 UTC, sighoya wrote:
> Immutable var in high level languages denote a value even if 
> this value consists of pointers.
> Most languages simply don't follow the model.

Not sure what you mean? In functional languages _everything_ is 
immutable. In imperative languages immutable tend to be only one 
level, not transitive?


> Usually, readonly is only a view of a variable, not a part of 
> type, so you can't change the value of a readonly variable 
> though the value can be changed from outside.

No, that would be "const", "readonly" does not allow changes 
after initialization.


> But what happens if I initialize a readonly variable with an 
> object which I mutate from the outside afterwards?

No problem.

But you cannot make the "var" point to a different object. It is 
locked to be a pointer to that memory address throughout the 
entire lifespan.


> In D you can only pass immutable parts into the initialization 
> of an immutable aggregate to prohibit any side effect.
> But is this the same behavior with readonly in Typescript, I 
> don't think so.

Not sure what you mean. "immutable" is transitive, so it is only 
allowed to point to "immutable". This is what "readonly" is 
supposed to relax. That is the whole point! :-)


>
> The proposed readonly in C# would be likewise non immutable as 
> shown from 
> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly:
>
>>Because reference types contain a reference to their data, a 
>>field that is a readonly reference type must always refer to 
>>the same object. That object isn't immutable.

This means that the pointer is immutable, but the pointed-to 
object is not immutable.

Same as the "readonly" that I propose as an addition to 
"immutable" for D.




More information about the Digitalmars-d mailing list