声明常量字符串[char] AA的语法是什么?

Abs*_*ype 5 associative-array d constants literals

以下声明:

const(string[char]) AA1 = [
    'a' : "fkclopel",
    'b' : "poehfftw"
];

void main(string args[]){}
Run Code Online (Sandbox Code Playgroud)

给我:

C:...\temp_0186F968.d(1,27):错误:非常量表达式['a':"fkclopel",'b':"poehfftw"]

而它适用于其他类型.

Gas*_*ssa 7

您可以在模块构造函数中初始化关联数组常量:

const /+ or immutable +/ (string [char]) AA1;
static this () {
    AA1 = [
        'a' : "fkclopel",
        'b' : "poehfftw"
    ];
}

import std.stdio;
void main () {writeln (AA1);}
Run Code Online (Sandbox Code Playgroud)

关联数组文字的手册部分明确指出"一个AssocArrayLite不能用于静态初始化任何东西.",尽管它没有提供关于它为什么如此的线索.

  • 原因是在当前的实现中(在许多方面是次优的),关联数组布局和其他细节对编译器完全不透明.AA文字只调用运行时函数(文件src/druntime/src/rt/aaA.d,函数_d_assocarrayliteralTX),它负责实际组织数据.该函数甚至可能在编译时不存在,稍后从二进制库链接.由于静态数据需要一个已知的布局,因此编译器可以将其放入可执行文件的数据段,并且此函数是一个黑盒子,它不能用于此. (8认同)