Construct an used-defined hash table container type from an AA-literal expression

Jacob Carlborg doob at me.com
Mon Jul 6 11:57:11 UTC 2020


On Monday, 6 July 2020 at 01:43:43 UTC, user1234 wrote:

> ---
> import std;
>
> struct AA
> {
>     void opIndexAssign(int v, string k) @nogc
>     {}
> }
>
> void main(string[] args) @nogc
> {
>     AA myCustom;
>
>     enum literal = ["one":1, "two":2].stringof[1..$-1];
>     enum pairs   = literal.split(',').array;
>     static foreach (p; pairs)
>     {
>         myCustom[mixin(p.split(':')[0])] = 
> mixin(p.split(':')[1]);
>     }
> }
> ---

`static foreach` actual works for AA literals in `@nogc` 
functions. So there's no need complicate things with `.stringof`:

struct Foo
{
     int a;
     int b;
}

enum literal = ["one": Foo(1, 2), "two": Foo(3, 4)];

struct AA
{
     void opIndexAssign(Foo value, string k) @nogc
     {
     }
}

void main() @nogc
{
     AA aa;

     static foreach (k, v; literal)
     {
         aa[k] = v;
     }
}



More information about the Digitalmars-d-learn mailing list