Non-transitive immutable? Read only struct.

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Fri Dec 6 09:26:40 UTC 2019


On Friday, 6 December 2019 at 09:11:11 UTC, Simen Kjærås wrote:
> On Thursday, 5 December 2019 at 17:01:07 UTC, Ola Fosheim 
> Grøstad wrote:
>
>> 1. Protect fields in structs/classes after initialization. 
>> Reduces bugs. Documents intent.
>
> immutable fields can be initialized in constructors.

But immutable fields cannot contain pointers to non-immutable 
memory?


> Getters allow you to define an interface that doesn't allow 
> modification by outside forces while still allowing the 
> class/struct to modify the fields if it feels like it, allowing 
> both non-reassignable fields and lazy initialization.

Making fields/attributes read only is not only for the external 
interface it is also documentation for internal use, to prevent 
accidental modification in the implementation, prevent 
inheritance issues, enables caching based on typing in generic 
programming.

>> 2. Turn received values from functions into something that 
>> cannot be modified reliably irrespective of what the 
>> protection the called function has set for it. Reduces bugs.
>
> Const does this. If you know it's immutable call assumeUnique 
> on it. If you want to limit modification in some ways while 
> allowing it in other ways, that sounds like a library thing, 
> not something the language should do for you.

No, const does not do it. If you receive a mutable value it will 
be const, not immutable. If you use immutable it will fail if the 
value contains an immutable pointer. (I am not talking about 
returned references, but value copies)

So there is no easy way to write this kind of code that has 
increased robustness in evolving codebases.


>> 3. To have sensible immutable tuples that can point to 
>> non-immutable things. In my view, a must have.
>
> Getters can be used for this.

That does not make the memory immutable as seen from the compiler?


>> 4. To have structures in ROM that can point to memory mapped 
>> registers or RAM. Not a must have, but sensible.
>
> Getters can do this. You'll probably have to dip into some 
> un- at safe code, but this seems like an exotic enough use case 
> that we can live with that.

Casting away immutable sounds very dangerous. If that can be done 
then the optimizer cannot use immutable for anything?

Anyway, getters are not useful in low level programming. You need 
to be able to take the address of the memory. So what you are 
left with is to leave it mutable to the typesystem and never 
write to it in your code, so basically no help from the type 
system.




More information about the Digitalmars-d mailing list