Search code examples
d

D language: variable s cannot be read at compile time


Hi I am having this issue when trying to compile a very simple D program:

#!/usr/bin/env rdmd
import std.uni;
import std.random : randomSample;
import std.stdio;
import std.conv;

/**
*  Random salt generator
*/
auto get_salt(uint s)
{
    auto unicodechars = unicode("Cyrillic") | unicode("Armenian") | unicode("Chinese");
    dchar[] unichars =  to!(dchar[])(unicodechars);
    dchar[s] salt;

    salt =  randomSample(unichars, s);
    return salt;
}

void main()
{
    writeln("Random salt");
    writeln(get_salt(32));
}

I get the following compilation error:

$ ./teste.d
./teste.d(13): Error: variable s cannot be read at compile time
Failed: ["dmd", "-v", "-o-", "./teste.d", "-I."]

@C-Otto's answoer below answer the question. However since there where still other bugs in the code I put below the simplified working version:

auto get_salt(uint s)
{
    auto unicodechars = unicode("Cyrillic") | unicode("Armenian") | unicode("Telugu");
    dstring unichars =  to!(dstring)(unicodechars);

    return randomSample(unichars, s);
}

void main()
{
    writeln("Random salt:");
    writeln(get_salt(32));
}

Solution

  • You define the length of the salt array to be s (so-called "static array"). This information needs to be available at compile time. However, the information is only available at run time, when you invoke the method and provide the argument named s.

    You can try defining the array without a specific size and create it at runtime ("dynamic array"), similar to unichars just in the line above.