[Feature request] Enum.lookup(value) support for cenums
It would be appreciated to be able to call lookup on a const enum type similar to how it used to work with inline associated members.
Example usage:
import std;
enum Foo : const
{
VAL1 = 1,
VAL2 = 2,
VAL42 = 42,
}
fn void main()
{
Foo f = Foo.lookup(42);
io::printfn("Value: %s", f);
}
Hmm.. what would be the use of this? Given that this works it will still just print 42.
Maybe you're thinking of a name lookup? In that case it would be more like:
fn void main()
{
Foo f = (Foo)42;
String name = f.lookup_name();
io::printfn("Value: %s", name);
}
Yeah sorry, some way of going back to the name of the enum entry, Foo.names[f.ordinal] would also work I suppose if that was supported again. I realize now that the way I wrote the original code was a little bit dumb :)
This was my temp solution
fn String Foo.get_name(&self)
{
for (int i = 0; i < Foo.values.len; ++i)
{
if (*self == Foo.values[i])
{
return Foo.names[i];
}
}
return "Unknown";
}
That one seems correct, although you can write it more succinctly as:
fn String Foo.get_name(&self)
{
foreach (i, &val : Foo.values)
{
if (*self == *val)
{
return Foo.names[i];
}
}
return "Unknown";
}
But you can also create a compile time foreach, like:
fn String Foo.get_name(&self)
{
$foreach $i, $foo : Foo.values:
if (*self == $foo) return Foo.names[$i];
$endforach
return "Unknown";
}
Is this feature needed still you think?