check variable for undefinedness
Jakob Ovrum
jakobovrum at gmail.com
Thu Dec 26 03:46:09 PST 2013
On Thursday, 26 December 2013 at 11:03:17 UTC, Dfr wrote:
> Here is what i trying to achieve, i have module-wise data
> structure, which should exist in form of array and associative
> array, but i can't calculate second form on compile time:
>
> const a = [["a","1"],["b", "2"], ... ];
> const string[string] b = a.map!(...).assocArray;
>
> This is not allowed, so i trying this approach:
>
> const a = [["a","1"],["b", "2"], ... ];
> const string[string] b;
>
> int some_func() {
> b = a.map!(...).assocArray;
> ....
> }
>
> It is ok, but i don't want calculate 'b' every time 'come_func'
> is called
Use a module constructor:
---
immutable a = [["a","1"], ["b", "2"]];
immutable string[string] b;
shared static this()
{
b = cast(immutable)a.map!(pair => tuple(pair[1],
pair[0])).assocArray;
}
---
Shared module constructors are called once, before the main
function. Non-shared module constructors are called once for
every thread - on the thread's creation (which, naturally, is
before main for the main thread), and should be used to
initialize TLS variables.
I took the liberty of changing the variables to be `immutable`.
When creating new data, `const` makes little sense - choose
either mutable or immutable.
A module constructor is the only place `immutable` or `const`
module-level variables without initalizers as part of their
declaration can be initialized.
The cast is required because the compiler fails to infer the
uniqueness of the initializer expression, but unique inference is
a work in progress, so this may (should) be allowed in the future.
More information about the Digitalmars-d-learn
mailing list