Defining Enums
Rust enums make C and C++ enums look like cardboard cutouts. Each variant can carry its own payload of different types and sizes — that's what makes them algebraic data types.
Simple Enums
enum Direction { North, South, East, West,}
let heading = Direction::North;Enums with Data
Each variant can carry data:
enum IpAddr { V4(u8, u8, u8, u8), V6(String),}
let home = IpAddr::V4(127, 0, 0, 1);let loopback = IpAddr::V6(String::from("::1"));Enums with Named Fields
Variants can have struct-like named fields:
enum Shape { Circle { radius: f64 }, Rectangle { width: f64, height: f64 }, Triangle { base: f64, height: f64 },}
let s = Shape::Circle { radius: 5.0 };Rust enums are the tagged-union pattern from C, made safe. C makes you wire up a struct with a discriminant field plus a union and trust yourself to read the right side. Rust hands the bookkeeping to the compiler, which guarantees you only ever see the data the active variant actually holds.
Put the two versions of Shape side by side and the bytes barely differ. On x86-64 both come to 24 bytes: a tag, padding up to 8-byte alignment, then 16 bytes of payload, enough for the largest variant. Rust doesn't promise this layout, but it's what rustc picks today, and std::mem::size_of::<Shape>() prints 24. Module 7 comes back to this with the disassembler open.
Methods on Enums
Enums can have methods, just like structs:
impl Shape { fn area(&self) -> f64 { match self { Shape::Circle { radius } => std::f64::consts::PI * radius * radius, Shape::Rectangle { width, height } => width * height, Shape::Triangle { base, height } => 0.5 * base * height, } }}
let shapes = vec![ Shape::Circle { radius: 5.0 }, Shape::Rectangle { width: 3.0, height: 4.0 },];
for shape in &shapes { println!("Area: {:.2}", shape.area());}Each Shape value is a tag plus enough room for its largest variant. Guess what size_of::<Shape>() prints before you run this.
Why that number?
On x86-64 it's 24. Rectangle needs 16 bytes for two f64s, and the tag gets padded out to 8 bytes so the floats stay aligned. Rust doesn't promise a layout for enums like this, so treat it as what today's compiler does rather than a rule.
The Option Enum
Rust has no null. There's Option<T> instead:
enum Option<T> { Some(T), None,}fn find_first_a(s: &str) -> Option<usize> { s.find('a')}
let result = find_first_a("banana");match result { Some(index) => println!("Found 'a' at index {}", index), None => println!("No 'a' found"),}Option makes the "no value" case unmissable. There's no way to accidentally treat a None as if it held something — the compiler stands in your way.