How expensive is an Enum item compared to an integer?

If I have a simple Enum like below. How expensive are those Enum items compared to integers?

Enum my_enum {
    A = 1,
    B,
    C
}

At run time, this enum has the same representation as a 1-byte integer like u8 or i8. (For enums with more than 256 variants, a wider type is used.)

So the Rust compiler is smart enough to optimize an Enum item to be essentially an integer while still maintain type safe?

Yes, in some cases the Rust compiler has built in knowledge about the memory layout of types and their invariants. I can't remember the exact term but by identifying unreachable bit patterns the memory layout of enums is optimized. E.g. the NonZero... types can not have all zeros as bit pattern so an Option<NonZeroU8> is has still std::mem::size_of::<u8>() (see the docs). The all zeros pattern is used to identify the None variant. Everything else must be a Some(_).
This also works for references there it is called null-pointer-optimization.

Yes, the type checks are done statically at compile time, and a (fieldless) enum compiles down to an integer.

What if there are methods defined for an Enum type?

Rust uses static dispatch, so method calls are no more expensive than normal function calls: There's never extra space allocated within the object for a method table.

(There is some method-call overhead if you're using trait objects, but that's a different topic)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.