本质上,我希望能够做这样的事情:
struct Foo
{
const(int)[2] ints;
this(int x, int y)
{
ints = [x, y];
}
}
但这不起作用。编译器 (DMD 2.048) 只是提示
ints
不可变。你应该如何初始化数组?
最佳答案
一种方法是实现构造函数是这样的:
this(int x, int y)
{
auto i2 = cast(int[2]*)&ints;
*i2 = [x, y];
}
const 是只读 View ,因此构造函数创建可变 View
i2
并分配给它。我真的不喜欢第一行的强制转换,也许 std lib 中有一些函数封装了强制转换并从变量类型中删除了 const 修饰符,所以这可以用安全和惯用的方式表达。第二种方法是使
ints
可变和私有(private),然后提供公共(public)访问器功能:struct Foo {
private int[2] _ints;
this(int x, int y) {
_ints = [x, y];
}
@property ref const(int)[2] ints () {
return _ints;
}
}
编译器可能能够内联它。
关于arrays - 如何在 D2 中初始化常量值数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3627023/