print enum value rather name from enum X : string

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Feb 12 17:29:47 UTC 2018


On Monday, February 12, 2018 17:07:50 Marc via Digitalmars-d-learn wrote:
> If I have an enum like this:
> > enum S  : string {
> >
> > foo = "a",
> > baa = "b"
> >
> >}
>
> when I printed it, to my surprise I get the enum field name
>
> rather value:
> > writefln("%s v%s", S.foo, S.baa);
>
> output:
> > foo vbaa
>
> instead of
>
> > a vb
>
> a cast solves it but without cast everywhere I need that enum
> member, is there any other way to do it? otherwise I'll have to
> switch to a class with static immutable strings, right?

If you actually use the enum values anywhere other than with anything from
std.conv, std.format, or std.stdio, then when they get converted to strings,
you get their actual values. It's just that those modules specifically grab
the names of the enum members when converting enums to strings, since in all
cases other than with strings, it's generally desirable that when converting
an enum member to string, you get the name - and with enums with a base type
of string, whether you want the name or the value depends on what you're
trying to do. Both can be useful.

So, when dealing with std.format, std.conv, and std.stdio, if you want an
enum of base type string to be treated as a string, then you'll have to
force it with a cast. Anywhere else, if they get converted to string, then
you'll get their values. If that is unacceptable for your use case for
whatever reason, then you'll have to try a different solution. What solution
would then work best would presumably depend on whatever it is you're
actually trying to do.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list