On Sunday, 20 February 2022 at 11:08:55 UTC, partypooper wrote:
Hello, I'm new to D.

Title is self described, is it possible to use keyword as struct field?

Maybe it is XYproblem, so here I will describe a little what I need. I'm parsing some json currently with [mir-ion](https://code.dlang.org/packages/mir-ion) (better/simpler suggestions for only json de/serialization?), that has "version" as one of it's keys, so I can't use that as field in my struct. Maybe some annotation in mir library to parse "version" into other struct field name, can't find though (its docs pretty concise).

I have a library solution based on opDispatch + __traits(getMember):

```d
/**
* Mixin template allowing to use a field as if its identifier is a D keyword.
 * Note that this only works with `__traits(getMember)`.
 * Params:
 *      keywordFieldPairs = An array of keyword and field pairs.
 */
template FieldOfKeyword(string[2][] keywordFieldPairs)
{
    template opDispatch(string member)
    {
        static foreach (pair; keywordFieldPairs)
            static if (member == pair[0])
                mixin("alias opDispatch = ", pair[1], ";" );
    }
}
///
unittest
{
    struct Foo
    {
mixin FieldOfKeyword!([["scope", "scope_"],["class", "class_"]]);
        string scope_;
        string class_;
    }

    Foo foo;
    __traits(getMember, foo, "scope") = "The Universe";
    assert(__traits(getMember, foo, "scope") == "The Universe");
    __traits(getMember, foo, "class") = "Atom";
    assert(__traits(getMember, foo, "class") == "Atom");
}
```

never used it TBH.

Reply via email to