Comparison of Enumerations with base type of String?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 26 19:11:13 PDT 2017


On Sunday, August 27, 2017 01:43:14 Michael Reiland via Digitalmars-d-learn 
wrote:
> Hey guys,
>
> I was running through a tutorial and I noticed that enums can
> have a base type of string.  Which is interesting, but I'm
> wondering about comparisons.
>
> I'm guessing the comparison boils down to a pointer comparison,
> but I thought I'd confirm.

No, it'll do the normal string comparison, just like enums that are ints do
a normal integer comparison. The fact the strings are enums doesn't really
change much except for stuff that's specifically doing something differently
for enums. It just means that instead of having separate constants which are
strings, you have them grouped together, and final switch statements will
require that the cases cover all of them. Some stuff like std.conv.to!string
or writeln will end up using the names of the enums rather than their values
like they do with other enums even though they're strings, but in general,
having

enum S : string
{
    foo = "yes",
    bar = "no",
}

isn't all that different from just doing

enum foo = "yes";
enum bar = "no";

except that declaring the enum S essentially puts them in a namespace called
S. It does create a new type S, which affects some stuff (e.g. S is not a
range, whereas string is), so operating an an S is not completely identical
to operating on a string, but S doesn't magically end up implementing
operations differently than occurs with string. It's just that some of the
operations on S are more restricted than a naked string, and since they
implicitly convert to string rather than being a string, some functions that
looks at the type will operate on an S differently than they would for a
naked string.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list