Rust C-Like Enums
A C-like enum is an enum whose variants are plain names, and each name stands for a number. A code, a level, or a colour value fits this shape.
Rust counts for you
A variant with no data gets a number, called its discriminant. The first variant is 0. The next is 1. And so on. Read the number back with a cast:
enum Number { Zero, One, Two }
println!("{} {} {}", Number::Zero as i32, Number::One as i32, Number::Two as i32);Choose your own numbers
Choose a number with =: the variant stores that exact value:
enum Colour { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff }
println!("roses are #{:06x}", Colour::Red as u32);Counting continues after a chosen number
After a chosen number, counting continues from it — gaps are allowed:
enum Level { Low = 2, Mid, High = 10, Top }
println!("{} {} {} {}", Level::Low as i32, Level::Mid as i32, Level::High as i32, Level::Top as i32);The cast goes one way only
The cast works one way only: enum to number. Turning a number back into a variant with as fails with error E0605 — use a match on the number instead:
let n = 1;
let word = match n { 0 => "zero", 1 => "one", _ => "many" };
println!("{} is {}", n, word);
// let back = 1 as Number; // error E0605: the cast does not run backwardsExample
enum Number { Zero, One, Two }
enum Colour { Red = 0xff0000, Green = 0x00ff00, Blue = 0x0000ff }
fn main() {
println!("zero is {}", Number::Zero as i32);
println!("one is {}", Number::One as i32);
println!("two is {}", Number::Two as i32);
println!("roses are #{:06x}", Colour::Red as u32);
println!("violets are #{:06x}", Colour::Blue as u32);
}In this example, Number chooses no numbers. So Rust counts for it. Zero is 0, One is 1, Two is 2. Colour chooses its numbers: each variant holds one colour code in hex. The as cast reads a number back out of a variant. The last two lines print the codes with {:06x}. That means hex with at least six digits. Roses are #ff0000 and violets are #0000ff.
Note
Only a variant that carries no data can be cast to a number.
A variant with data inside has no plain number: pull the data out with match instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What is Number::Two as i32, when Number is Zero, One, Two?