Sub topic 16
C-like enums, discriminants, and casting
This chapter assumes you know how to define enums, use match, and derive traits such as Debug. It covers enums whose variants carry no data, the integer value behind each variant, and how to convert between the two.
C-like enums and discriminants
A C-like enum has only unit variants, meaning variants with no data. Every variant of an enum has a hidden integer called its discriminant. By default, the first variant gets 0 and each later variant gets the previous value plus one. You can assign explicit values with =. Any variant without an explicit value continues counting from the one before it.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Level {
Low = 1,
Medium = 5,
High = 10,
}
fn main() {
let level = Level::Medium;
println!("{:?} = {}", level, level as i32);
}This prints Medium = 5. The as cast reads the discriminant of the variant and converts it to the integer type you name.
Casting works in one direction
You can cast an enum to an integer with as. You cannot cast an integer to an enum with as. Not every integer is a valid variant, so the compiler refuses 5 as Level.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Level {
Low = 1,
Medium = 5,
High = 10,
}
impl TryFrom<i32> for Level {
type Error = String;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
1 => Ok(Level::Low),
5 => Ok(Level::Medium),
10 => Ok(Level::High),
other => Err(format!("{other} is not a valid level")),
}
}
}
fn main() {
println!("{:?}", Level::try_from(5));
println!("{:?}", Level::try_from(7));
}The program prints Ok(Medium) and then Err("7 is not a valid level"). The conversion returns a Result, so the caller must handle the invalid case. This is the same idea as the Result and From conversions from earlier chapters.
Choosing the integer type
By default the discriminant type is isize, but a cast such as level as u8 truncates the value if it does not fit. To fix the storage size, add a repr attribute.
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
fn main() {
println!("{}", Color::Blue as u8);
println!("{}", std::mem::size_of::<Color>());
}This prints 4 and then 1. With #[repr(u8)], the enum takes exactly one byte, and the compiler rejects discriminants that do not fit in a u8. This matters when you share data with C code or write bytes to a file or network protocol.
Rules to remember
- Two variants of one enum cannot have the same discriminant. The compiler reports an error.
- Discriminants may be negative if the representation type is signed.
- Enums with data in some variants can also have explicit discriminants, but only with a
reprattribute. Most code does not need this. - Deriving
PartialEqlets you compare variants with==. Comparing the cast integers is rarely necessary. - Use
Copyon C-like enums. They are small, so passing them by value is cheap and avoids move errors.
Exercise
Given enum Step { A = 3, B, C = 10, D }, what do Step::B as i32 and Step::D as i32 evaluate to?
Show answer
Step::B as i32 is 4 and Step::D as i32 is 11. A variant without an explicit value takes the previous discriminant plus one.
Exercise
Why does let l = 5 as Level; fail to compile, and what is the safe alternative?
Show answer
An integer may match no variant, so Rust does not allow as to produce an enum. Implement TryFrom<i32> for Level and call Level::try_from(5), which returns a Result that you must handle.