How to initialize immutable variables with an expression that throws an exception to catch?

tsbockman thomas.bockman at gmail.com
Tue Apr 7 19:52:36 UTC 2020


On Tuesday, 7 April 2020 at 14:15:20 UTC, FeepingCreature wrote:
> Right, but that's still the exact same workaround, except with 
> Nullable instead of Algebraic. I know how to work around it. 
> I'm saying what should be changed in the language so I don't 
> *have to* work around it?

The problem in the language is that immutability is considered a 
permanent and fundamental property of a value, whereas it is 
actually a state that is entered after the 
initialization/construction of the value is complete, and exited 
when the value's memory is later reclaimed.

Construction of an immutable value should be done by making a 
mutable variable, mutating it to the desired state via any 
arbitrary sequence of normal operations, and then declaring the 
mutable stage of its life cycle complete via `cast(immutable)` or 
something. The only problem with this is making the compiler 
smart enough to prove that no mutable references to the data are 
used after that point, so that the operation can be @safe.

The current rules for immutable constructors are sort of like 
this, but they're still overly strict to the point that I often 
need to make the constructor @trusted and use (cast() this) to 
get the job done without excessive reliance on the optimizer, or 
excessive code duplication. Also, not everything can or should be 
done in a constructor.


More information about the Digitalmars-d mailing list