On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote:
I am new in D, and started this morning. I found a way to read
a file at compile time with `-J.` and `static string content =
import("my_json_file.json")`
static usually means "give this declaration the same semantics as
if it were at global scope". So:
```D
void main()
{
static struct S
{
int x, y;
}
static string v;
static void fun()
{
}
}
// Same meaning as these declarations:
struct S
{
int x, y;
}
string v;
void fun()
{
}
```
This turns local variables into global variables, and nested
functions which usually can access local variables into functions
without access to locals.
When you add `static` to a variable that is already at global
scope, it does nothing.
The confusion is understandable, because `static` has a million
other meanings across programming languages. For example, in C
and C++, static global variables/functions do have a meaning,
which is similar to D's `private`. Also, `static if` and `static
foreach` do imply compile time execution in D, but to enforce
compile time execution on a variable, you need the `enum` or
`immutable` keyword.
```D
immutable string content = import("my_json_file.json")
// Or inside a function:
void main()
{
static immutable string content = import("my_json_file.json")
}
```
My goal is to have a JSONValue at runtime that would be already
present in the binary. Cause the JSONValue is huge. Like
megabytes of data...
Be careful that Compile Time Function Execution (CTFE) is not
very performant, so parsing a large JSON string at compile time
can be very slow and RAM hungry. If you're using dub to build
your program, you might want to put the JSON object into its own
package so it will be cached, and you won't have to wait so long
for your build to finish every time.