How to iterate string enum values?
Jim Balter
jqbalter at gmail.com
Mon Dec 23 23:46:33 UTC 2024
On Monday, 23 December 2024 at 20:32:58 UTC, Anton Pastukhov
wrote:
> On Monday, 23 December 2024 at 20:26:47 UTC, bauss wrote:
>
>> Simply cast el to a string instead of using std.conv.to
>
> Thanks much, it worked! Though I'm confused why. Could you
> please elaborate?
I had the exact same issue yesterday. Allow me to quote ChatGPT:
You're correct that .to!string also produces the member name
rather than the value of the enum, which can be confusing. This
behavior occurs because .to!string calls the toString function
defined for the enum type, which defaults to returning the name
of the enum member rather than its associated value.
Why .to!string behaves this way:
Enums in D are designed to emphasize their symbolic names over
their values. The toString implementation for enums is tailored
to reflect this by default, focusing on member names instead of
their underlying values. The std.conv.to function, when applied
to an enum, invokes this toString behavior.
Correct way to get the value:
If you want to convert the underlying value of the enum member to
a string, you must explicitly cast the enum to its base type.
More information about the Digitalmars-d-learn
mailing list