c3c icon indicating copy to clipboard operation
c3c copied to clipboard

[Feature request] Enum.lookup(value) support for cenums

Open TechnicalFowl opened this issue 5 months ago • 5 comments

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);
}

TechnicalFowl avatar Jul 02 '25 04:07 TechnicalFowl

Hmm.. what would be the use of this? Given that this works it will still just print 42.

lerno avatar Jul 02 '25 23:07 lerno

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);
}

lerno avatar Jul 02 '25 23:07 lerno

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";
}

TechnicalFowl avatar Jul 03 '25 00:07 TechnicalFowl

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";
}

lerno avatar Jul 03 '25 11:07 lerno

Is this feature needed still you think?

lerno avatar Oct 09 '25 23:10 lerno