Comment #0 by bearophile_hugs — 2011-11-08T19:24:43Z
A correct D2 program that defines a global immutable array of enum members:
enum MyEnum { first, second }
immutable MyEnum[] array = [MyEnum.first,MyEnum.second,MyEnum.second,
MyEnum.first,MyEnum.second,MyEnum.second];
void main() {}
To reduce the noise I'd like to use with() at global scope too (there is no need to call is "static with"):
enum MyEnum { first, second }
with (MyEnum) {
immutable MyEnum[] array = [first,second,second,first,second,second];
}
void main() {}
with is useful for global structs too.
Comment #1 by bearophile_hugs — 2011-11-09T05:12:18Z
This is a workaround, but I try to avoid static this where possible to avoid circular reference import troubles:
enum MyEnum { first, second }
immutable MyEnum[] array;
static this() {
with (MyEnum)
array = [first,second,second,first,second,second];
}
void main() {}
Comment #2 by bearophile_hugs — 2013-11-24T08:27:41Z
Such "static with" that doesn't create a new scope is also useful to define constant arrays:
void main() {
enum LongNamedEnum { A, B, C, D }
const int[LongNamedEnum] foo =
[LongNamedEnum.A: 10, LongNamedEnum.B: 20,
LongNamedEnum.C: 30, LongNamedEnum.D: 40];
}
with is usually useful to write such array literals in a shorter space, but you can't also define the assopciative array as const:
void main() {
enum LongNamedEnum { A, B, C, D }
/*const*/ int[LongNamedEnum] foo;
with (LongNamedEnum)
foo = [A: 10, B: 20, C: 30, D: 40];
}
void main() {
enum LongNamedEnum { A, B, C, D }
static with (LongNamedEnum)
const int[LongNamedEnum] foo =
[A: 10, B: 20, C: 30, D: 40];
}
Comment #3 by dkorpel — 2021-09-08T13:43:07Z
I like the idea too. The workaround I currently use is this:
```
private alias L = LongNamedEnum;
immutable LongNamedEnum[] array = [L.first, L.second, L.second];
```
Comment #4 by robert.schadek — 2024-12-13T17:56:53Z