Disambiguate enum variant and constant?

Rust allows you to create an enum with a variant name and an associated constant of the same name:

enum Foo {
    Bar,
}

impl Foo {
    const Bar: u8 = 1;
}

However, I can't figure out if there's any way to refer to the constant by name (e.g., see here). Both Self::Bar and Foo::Bar seem to refer to the variant. Is there any way around this?

Tried for 30 minutes and haven't managed to figure it out. What are you using this for by the way?
It is possible to specify the enum representation, in case it solves your use case:

Maybe trying to do something like this, but have nicer names instead of numbers (playground):

impl From<u8> for Foo {
    fn from(u: u8) -> Foo {
        match u {
            1 => Foo::Bar,
            u => Foo::Other(u),
        }
    }
}

Personally I'd use a proc macro, but it may be over the top

1 Like

This might not be possible. However, in actual use, collisions seem unlikely due to Rust's naming recommendations.

2 Likes

I was working on a macro to create enums where each variant corresponds to a particular value of a u8; something like this:

enum IpProto {
    Tcp,
    Udp,
    Other(u8),
}

impl IpProto {
    const TCP: u8 = 6;
    const UDP: u8 = 17;
}

impl From<u8> for IpProto {
    fn from(u: u8) -> IpProto {
        match u {
            Self::TCP => IpProto::Tcp,
            Self::UDP => IpProto::Udp,
            u => IpProto::Other(u),
        }
    }
}

impl Into<u8> for IpProto { ... }

I wanted to avoid having the user to have to specify both the variant name (Tcp) and the constant name (TCP). However, I ended up realizing that I could just use the numeric values directly without using constants at all. The constants made sense before when we were writing these by hand and didn't want to make a mistake in writing down numeric literals, but they don't make sense when we're automatically generating the code from a macro. So it's not an issue I need to solve anymore.

For the curious, here's what I ended up coming up with.

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