Type numeric enums as string literals or undefined

This feature would represent every variant, in a numeric enum, as a pair (str, num). The str would be a compile identifier, allowing for the user to select the proper coding style.

enum E {
    SomeVariant = 0, // ("some_variant", 0)
    AeonDropdown = ("aeon", 0x7f),

let e: E = "aeon";
println!(e as u32); // 0x7f

let e: E = "zxc"; // verify error: undefined variant

For flags-only enum:

let f: F = ();

These would be implicit conversions from string or undefined constant to enum E or Option<E>!

This doesn't mean one can write something like let f: F = str;. The suggestion is to allow lookuping enum variant using string literal (or string constant value) through type inference.

I doubt this should be implicit, but strum is good for this.

1 Like

@cuviper This seems a bit verbose as you'd need to call Enum::from_str("id") everytime you want to simply use a string literal. You even need to lookup the enum.

Yes, just like you have to make an explicit call if you want to convert a string to an integer.

1 Like

Actually the goal is to be able to use a string literal as a lookup for an enum variant, not any dynamically obtained string. Inclusively, when the string literal does not recognize a valid variant, the compiler may report a verify error.

Why use a string for this at all, and not a real identifier? You could have something like:

const AEON: E = E::AeonDropdown;

A proc-macro could even generate these for each variant, with automatic names or with attributes choosing specific names, much like what strum allows.


This is what I'd use, but the only issue is that it may conflict when there is more than one enum in scope. I think using the type inference is a good solution as well.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.