初始化struct值和字符串键的关联数组

Mat*_*tej 5 associative-array d initialization

(对于"D"编程语言)

我一直在努力尝试初始化一个具有struct元素的关联数组,并且应该可以通过字符串索引.我会从单独的文件中将其作为模块导入.

这是我想要实现的(它不起作用 - 我不知道这是否可能):

mnemonic_info[string] mnemonic_table = [
        /* name,         format,          opcode */
        "ADD": {mnemonic_format.Format3M, 0x18},
        ...

        /* NOTE: mnemonic_format is an enum type. */
        /* mnemonic_info is a struct with a mnemonic_format and an ubyte */
];
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于可由整数索引的数组.

最理想的是,我希望在编译时对其进行评估,因为我不会改变它.但是,如果不可能的话,如果你告诉我在即时运行时/之前构建这样一个数组的最佳方法,我会很高兴的.

我需要这个,因为我正在写一个汇编程序.

我搜索了SO和互联网的答案,但只能找到整数的例子,以及其他我不理解或无法工作的东西.

到目前为止我真的很喜欢D,但由于网上没有很多教程,所以我觉得很难学.

谢谢!

旁注:是否可以将元组用于关联数组元素而不是自定义结构?

编辑

到目前为止我找到了一种方法,但它非常难看:

mnemonic_info[string] mnemonic_table;
static this() { // Not idea what this does.
        mnemonic_info entry;

        entry.format = mnemonic_format.Format3M;
        entry.opcode = 0x18;
        mnemonic_table["ADD"] = entry;

        /* ... for all entries. */
}
Run Code Online (Sandbox Code Playgroud)

Nek*_*nto 6

在D中,内置的关联数组文字总是在运行时创建,因此通过在声明位置为其分配一些值来初始化全局关联数组是不可能的.

正如您自己发现的那样,您可以通过在模块构造函数中为关联数组赋值来解决这个问题.

代码中的另一个问题是struct initialization literals.你应该更喜欢D风格的 struct初始化器到C风格的初始化器.

例:

struct Foo {
    int a;
    string b;
}

Foo[string] global;

static this() {
    global = [
        "foo" : Foo(1, "hurr"),
        "bar" : Foo(2, "durr")
    ];
}

void main() {
    assert(global["foo"].a == 1);
}
Run Code Online (Sandbox Code Playgroud)