prosseek
prosseek

Reputation: 191099

Printing the enum string values (not keys) in D

I print "F" not "Fahrenheit" in this code. How can I print the enum value not the key?

import std.stdio;

void main()
{
    enum TemperatureUnit : string { C = "Celsius", F = "Fahrenheit" }
    writefln("%s", TemperatureUnit.F);
}

Upvotes: 0

Views: 97

Answers (1)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

Simply cast it to a string:

writefln("%s", cast(string) TemperatureUnit.F);

Note that this cast is NOT necessary when assigning it to a string:

string s = TemperatureUnit.F; // just works

It only comes into play here because the std.stdio.write* family of functions, as well as std.conv.to, look at the exact type passed to it and try to specialize on it. When it is enum Color { red, green, blue }, printing out the name is useful. But that behavior is less helpful when the value is a printable string too. Casting tells the function you want it treated like a plain string rather than an enum.

Upvotes: 1

Related Questions