Reputation: 191099
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
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