"inline" conversion of array to immutable

Jeff Thompson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 22 02:25:32 PDT 2016


Hello. The following code compiles OK where func creates a 
mutable array and main assigns it to an immutable variable:

int[] func(int x) pure {
   int[] result = new int[10];
   result[0] = x;
   return result;
}

void main(string[] args)
{
   immutable int[] array = func(1);
}

I assume this works because func is pure so that the compiler 
knows that its return value won't be changed by some other code. 
But it doesn't compile when I put the same code from func 
"inline" into main:

void main(string[] args)
{
   int[] result = new int[10];
   result[0] = 1;
   immutable int[] array = result;
}

I could forcibly cast result to immutable int[], but that seems 
error-prone. How to tell the compiler that result will not be 
changed after assigning to array so that the immutable assignment 
compiles?


More information about the Digitalmars-d-learn mailing list