Sub topic 16
C-like enums, discriminants, and casting
This chapter covers enums whose variants carry no data, the integer each variant is tagged with, and how to convert between the two. It assumes you can define an enum and write a match over it, and that you know how Result and the TryFrom trait are used at a basic level.
What a C-like enum is
A C-like enum has only unit variants, meaning variants with no fields. The name comes from C's enum, which is just a set of named integer constants. Rust's version is a real type, but it keeps one feature of the C design: each variant has a discriminant, an integer that identifies it.
You can usually ignore discriminants. They matter when you:
- exchange values with a file format, network protocol, or C library that uses numeric codes,
- need a stable numeric value for a variant,
- want to use a variant as an array index.
Implicit and explicit discriminants
If you assign nothing, the first variant gets 0 and each later variant gets the previous value plus one. You can assign a value to any variant with =. Variants after it continue counting from that value.
#[derive(Debug, Clone, Copy)]
enum Weekday {
Mon,
Tue,
Wed = 10,
Thu,
Fri,
}
fn main() {
let days = [
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
];
for day in days {
println!("{:?} = {}", day, day as i32);
}
}This prints Mon = 0, Tue = 1, Wed = 10, Thu = 11, and Fri = 12.
Two rules apply:
- Two variants cannot share a discriminant. The compiler reports an error for duplicates, including duplicates that come from the counting rule.
- Discriminants must be integer constant expressions. Negative values are allowed.
Casting a variant to an integer
The as operator converts a fieldless enum value into an integer. The example below is the one from the plan for this tutorial.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Level {
Low = 1,
Medium = 5,
High = 10,
}
fn main() {
let level = Level::Medium;
println!("{:?} = {}", level, level as i32);
}The output is Medium = 5.
Keep these points in mind:
asworks only on enums where every variant is a unit variant. An enum with a tuple or struct-like variant, such asShapefrom earlier chapters, fails with a "non-primitive cast" error.- If you cast to an integer type too small for the discriminant, the value is truncated without warning.
Level::High as u8is fine, but a discriminant of300cast tou8becomes44. Pick a target type that fits. - Casting a non-
Copyenum moves it. DeriveCloneandCopyon C-like enums so a cast does not consume your value.
Casting the other way is not allowed
There is no as conversion from an integer to an enum. Writing 5 as Level is a compile error. This is deliberate. An integer such as 7 has no matching variant in Level, and Rust will not let you build a value that is not one of the declared variants.
The safe way back is to write the conversion yourself. Implement TryFrom and use match with a catch-all arm for invalid numbers. The compiler then checks that you handled every variant, and callers must handle the failure case.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Level {
Low = 1,
Medium = 5,
High = 10,
}
impl TryFrom<u8> for Level {
type Error = u8;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(Level::Low),
5 => Ok(Level::Medium),
10 => Ok(Level::High),
other => Err(other),
}
}
}
fn main() {
println!("{:?}", Level::try_from(5));
println!("{:?}", Level::try_from(7));
let parsed: Result<Level, _> = 10u8.try_into();
println!("{:?}", parsed);
}The output is:
Ok(Medium)
Err(7)
Ok(High)Implementing TryFrom<u8> also gives you TryInto<Level> on u8 for free, which is what 10u8.try_into() uses.
Keeping the two directions in sync
The numbers 1, 5, and 10 now appear twice: in the enum and in the match. If someone changes one and forgets the other, the conversion silently disagrees with the cast. Two defenses help:
- Use the enum's own discriminants in the match arms through constants, for example
x if x == Level::Low as u8 => Ok(Level::Low). This costs readability but keeps one source of truth. - Write a small unit test that loops over every variant and checks
Level::try_from(v as u8) == Ok(v).PartialEqandDebugon the enum make this assertion easy to write.
Third-party crates such as num_enum generate this boilerplate, but the manual version needs no dependency and is only a few lines.
Choosing the integer type with `repr`
By default, the compiler picks the size of the enum's tag and does not promise which one. If a value crosses a boundary where the layout matters, state the representation with the repr attribute.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
enum Level {
Low = 1,
Medium = 5,
High = 10,
}
fn main() {
println!("size: {} byte(s)", std::mem::size_of::<Level>());
println!("{}", Level::High as u8);
}With #[repr(u8)]:
- the tag is exactly one byte, so the program prints
size: 1 byte(s), - every discriminant must fit in a
u8, and the compiler rejects ones that do not, - the enum has the layout that C code or a binary format can rely on.
Other options include repr(i32), repr(u16), and repr(C). Use repr(C) or a fixed integer type when you pass the enum through FFI (calls to C code). Without a repr, do not assume the enum's size or tag layout.
Discriminants beyond fieldless enums
Enums with data also have discriminants, but you cannot read them with as. Since Rust 1.66 you can assign explicit discriminants to an enum with fields if you also add a repr such as #[repr(u8)]. You still cannot cast such a value with as. In practice, treat discriminants as a feature of C-like enums and use match for everything else.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `5 as Level` | Compile error | Implement `TryFrom<u8>` |
| `Shape::Circle { radius: 1.0 } as i32` | Compile error, non-primitive cast | Use `match`, or give the enum only unit variants |
| Casting to a too-small integer | Value silently truncated | Use a type that fits, or `repr` the enum |
| Two variants with the same value | Compile error | Give each variant a distinct discriminant |
| `std::mem::transmute` from an integer to an enum | Undefined behavior if the number is not a valid variant | Use `TryFrom` and a `match` |
| Adding a variant but forgetting `try_from` | Compiles with the catch-all arm, rejects the new number | Add a test that checks every variant round-trips |
Discriminants and ordering
If you derive PartialOrd and Ord on a C-like enum, variants compare by their discriminants. With Level, Level::Low < Level::High is true because 1 < 10. If you reorder variants or change their values, you change the ordering. Check that this is what you want before deriving it, particularly if the numbers come from an external format and the declaration order differs.
Using an enum as an index
Casting to usize is a common way to index a lookup table without a match:
#[derive(Debug, Clone, Copy)]
enum Color {
Red,
Green,
Blue,
}
fn main() {
let names = ["red", "green", "blue"];
for color in [Color::Red, Color::Green, Color::Blue] {
println!("{:?} -> {}", color, names[color as usize]);
}
}This is safe as long as the array has one entry per variant and the discriminants stay at their default values 0, 1, 2. If you later add a variant or give one an explicit value, the index can go out of bounds and panic at run time. A match returning the string has no such risk, and the compiler checks it for exhaustiveness. Prefer the cast only when a table is clearly the better fit, and keep a comment next to the enum.
Exercise
You have #[repr(u8)] enum Op { Add = 1, Sub = 2, Mul = 3 } and receive a u8 from a network packet. Write the signature and the match arms for converting the byte into an Op, and say what the function should do for the byte 9. Why not use as?
Show answer
Implement impl TryFrom<u8> for Op { type Error = u8; fn try_from(b: u8) -> Result<Self, u8> { match b { 1 => Ok(Op::Add), 2 => Ok(Op::Sub), 3 => Ok(Op::Mul), other => Err(other) } } }. For 9 the function returns Err(9), so the caller must decide how to handle bad input. as cannot convert an integer into an enum at all, because Rust does not allow a value that is not one of the declared variants.
Exercise
Given enum Code { A = 3, B, C = 3 }, what happens when you compile it, and why?
Show answer
It does not compile. B gets the implicit value 4, but C is explicitly 3, which duplicates A. Rust rejects two variants with the same discriminant.