New feature proposal: "initialization scope"

TommiT tommitissari at hotmail.com
Thu May 16 00:53:06 PDT 2013


I'd like to make it easier to initialize function local 
immutable/const data. Here's the type of problem I'd like to 
alleviate:

const string[100] int__str;
const int[string] str__int;

for (int i = 0; i < 100; ++i)
{
     auto str = to!string(i);
     int__str[i] = str; // ERROR: Can't modify const
     str__int[str] = i; // ERROR: Can't modify const
}

In short, I want to initialize two different const variables at 
once (in the same loop or other block). If I needed to initialize 
only one const variable, I could use a lambda:

const string[100] int__str = {
     string[100] tmp;
     // ... init tmp ...
     return tmp;
}();

...But I can't see any easy solution for initializing two or more 
const variables at the same time.

Here's my proposal: "initialization scope". You'd use it like 
this:

initialization {
     const string[100] int__str;
     const int[string] str__int;

     for (int i = 0; i < 100; ++i)
     {
         auto str = to!string(i);
         int__str[i] = str; // OK
         str__int[str] = i; // OK
     }
}

string s = int__str[42]; // OK
int__str[42] = "43" // ERROR: Can't modify const

As you can see, 'initialization scope' would be a scope that is 
not a lexical scope (like static if), it merely makes all const 
and immutable variables created in that scope modifiable inside 
that scope but not after it.


More information about the Digitalmars-d mailing list