Proper way to protect (lock) a struct field after initialization ??

Ali Çehreli acehreli at yahoo.com
Sun Aug 8 10:40:51 UTC 2021


On 8/8/21 3:11 AM, james.p.leblanc wrote:
> Hello All.
> 
> Is there a standard way to protect a field of a struct after
> the struct has been initialized?
> 
> Is this possible with a struct?
> 
> If not, I suppose a class (object) would be needed?  If so,
> are there any simple pointers to an example of this?
> 
> Thanks in advance,
> 
> James
> 

I understand your question differently from jfondren. You may be looking 
for a 'const' (or 'immutable') member:

struct S {
   const int i;

   this(int i) {
     // This will work because "first assignment is initialization"
     this.i = i;
   }
}

void main() {
   auto s = S(42);

   // This won't work
   s.i = 43;

   // This won't work either
   s = S(44);
}

Ali



More information about the Digitalmars-d-learn mailing list