Created
September 23, 2020 19:54
-
-
Save PetarKirov/cb6bdb083c36ab8f1b99c0289550c36c to your computer and use it in GitHub Desktop.
Global immutable associative array variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() {} | |
immutable string[ubyte] valueTypes; | |
// This is a shared module constructor. Code in this block will be executed | |
// exactly once at application startup. It is similar to running code in the | |
// global scope in JavaScript. Shared module constructors are allowed to | |
// "mutate" immutable global variables in order to initialize them. | |
shared static this() | |
{ | |
assert(!valueTypes); // The AA is initialized to null | |
valueTypes = [ | |
0x7F: "i32", | |
0x7E: "i64", | |
0x7D: "f32", | |
0x7C: "f64" | |
]; | |
} | |
pure unittest | |
{ | |
/* | |
* (1) `valueTypes` is considered immutable for all intents and purposes | |
* after the module constructor have been executed and the program | |
* execution has started. | |
* (2) pure function cannot access global variables, unless they're | |
* immutable => OK | |
*/ | |
auto aa1 = valueTypes; | |
auto aa2 = valueTypes; | |
assert(aa1 is aa2); // aa1 and aa2 point to *the same* object | |
assert(aa1 == aa2); | |
assert(aa1 == cast(immutable string[ubyte])[ 0x7F: "i32", 0x7E: "i64", 0x7D: "f32", 0x7C: "f64" ]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment