D语言:编译时无法读取变量s
D language: variable s cannot be read at compile time
您好,我在尝试编译一个非常简单的 D 程序时遇到了这个问题:
#!/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));
}
我得到以下编译错误:
$ ./teste.d
./teste.d(13): Error: variable s cannot be read at compile time
Failed: ["dmd", "-v", "-o-", "./teste.d", "-I."]
@C-Otto 下面的回答者回答了这个问题。但是,由于代码中还有其他错误,我将其放在简化的工作版本下方:
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));
}
你定义salt
数组的长度为s
(所谓"static array")。此信息需要在编译时可用。但是,该信息仅在 运行 时间可用,当您调用该方法并提供名为 s
.
的参数时
您可以尝试定义没有特定大小的数组并在 运行 时间创建它 ("dynamic array"),类似于上面一行中的 unichars
。
您好,我在尝试编译一个非常简单的 D 程序时遇到了这个问题:
#!/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));
}
我得到以下编译错误:
$ ./teste.d
./teste.d(13): Error: variable s cannot be read at compile time
Failed: ["dmd", "-v", "-o-", "./teste.d", "-I."]
@C-Otto 下面的回答者回答了这个问题。但是,由于代码中还有其他错误,我将其放在简化的工作版本下方:
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));
}
你定义salt
数组的长度为s
(所谓"static array")。此信息需要在编译时可用。但是,该信息仅在 运行 时间可用,当您调用该方法并提供名为 s
.
您可以尝试定义没有特定大小的数组并在 运行 时间创建它 ("dynamic array"),类似于上面一行中的 unichars
。