June 08, 2020 non-constant expression while initializing two dim array | ||||
---|---|---|---|---|
| ||||
How can I initialize my two dimensional array? When I try to run the code below I get the error: Error: non-constant expression ["user":[cast(Capability)0], "administrator":[cast(Capability)1]] Code: enum Capability { self, administer } alias Capabilities = immutable Capability[]; private Capabilities[string] roleCapabilities = [ "user" : [Capability.self], "administrator" : [Capability.administer] ]; I have tried adding more const and immutable prefixes but it still gives me the same error. The goal is that roleCapabilities should be an immutable/const two dimensional array. |
June 08, 2020 Re: non-constant expression while initializing two dim array | ||||
---|---|---|---|---|
| ||||
Posted in reply to tirithen | On Monday, 8 June 2020 at 06:37:18 UTC, tirithen wrote:
> How can I initialize my two dimensional array?
>
> When I try to run the code below I get the error:
>
> Error: non-constant expression ["user":[cast(Capability)0], "administrator":[cast(Capability)1]]
>
> Code:
>
> enum Capability {
> self,
> administer
> }
>
> alias Capabilities = immutable Capability[];
>
> private Capabilities[string] roleCapabilities = [
> "user" : [Capability.self], "administrator" : [Capability.administer]
> ];
>
> I have tried adding more const and immutable prefixes but it still gives me the same error. The goal is that roleCapabilities should be an immutable/const two dimensional array.
What you declare here is not a two dim array it's an associative array.
Associative array implementation have limitations. To initialize one that doesn't have const expr as key you can use a static module constructor:
---
enum Capability {
self,
administer
}
alias Capabilities = immutable Capability[];
private Capabilities[string] roleCapabilities;
static this()
{
roleCapabilities = [
"user" : [Capability.self], "administrator" : [Capability.administer]
];
}
---
which is done at runtime, just before the D main() get executed.
Notes:
1. You can also use a function containing a switch statement instead of an assoc array.
2. the other way would work because it would be a static array, the enum member giving an integer index:
---
enum Capability {
self,
administer
}
alias Capabilities = immutable Capability[];
private string[Capability.max + 1] roleCapabilities = [
Capability.self : "user",
Capability.administer : "administrator",
];
---
but I suppose that is different.
|
Copyright © 1999-2021 by the D Language Foundation