Module 5 · Structs, methods & enums
5.2Enums with data
How Rust enums go beyond named numbers, with variants that each carry their own data, methods, and a match the compiler checks is complete.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A fixed set of names | A string literal union: "red" | "green" | enum Light { Red, Green }, named integers | enum Light { Red, Green } |
| One of several shapes, each with its own data | A discriminated union with a kind tag | An abstract record with a sealed record per case | An enum whose variants carry fields |
| Handling each case | switch (value.kind) | switch expression with type patterns | match |
| A case you forgot | A compile error only if the return type or a never check forces it | A warning, so you add _ => throw | Compile error E0004 |
| A value outside the list | Ruled out by the type checker | Allowed: (Light)42 compiles and runs | Impossible |
| A value that may be missing | T | undefined | T? | Option<T>, an ordinary enum |
The word enum means something different in Rust. In C#, an enum is a set of names for integers.In TypeScript, an enum gives names to numbers or strings. In Rust, an enum is a type whose value is exactly one of several variants, and each variant can carry its own data. The closest thing in TypeScript isn’t its enum at all, but a discriminated union: a union of object types with a kind tag.The closest thing in C# isn’t its enum at all, but a small record hierarchy: an abstract record with a sealed record for each case. Rust builds that pattern into the language, adds methods, and checks that every match handles every case.
More than named numbers
At their simplest, Rust enums look like a union of string literalsC# enums: a list of names. Here’s a traffic light with one method:
type Light = "red" | "yellow" | "green";
function durationSecs(light: Light): number {
switch (light) {
case "red":
return 30;
case "yellow":
return 5;
case "green":
return 25;
}
}
const lights: Light[] = ["red", "yellow", "green"];
for (const light of lights) {
console.log(durationSecs(light));
}Light[] lights = [Light.Red, Light.Yellow, Light.Green];
foreach (var light in lights)
{
Console.WriteLine(DurationSecs(light));
}
static int DurationSecs(Light light) => light switch
{
Light.Red => 30,
Light.Yellow => 5,
Light.Green => 25,
_ => throw new ArgumentOutOfRangeException(nameof(light)),
};
enum Light { Red, Yellow, Green }enum Light {
Red,
Yellow,
Green,
}
impl Light {
fn duration_secs(&self) -> u32 {
match self {
Light::Red => 30,
Light::Yellow => 5,
Light::Green => 25,
}
}
}
fn main() {
let lights = [Light::Red, Light::Yellow, Light::Green];
for light in &lights {
println!("{}", light.duration_secs());
}
}Output
30 5 25
Two differences already show:
- Methods. A Rust enum gets an
implblock, just like a struct, soduration_secsbelongs toLight. A C# enum can’t declare methods; you write a static helper or an extension method.A string union can’t have methods; you write a separate function likedurationSecs. - No default arm. Without
_ => throw, the C#switchexpression warns (CS8524) and can throwSwitchExpressionExceptionat run time, because a C# enum is only anintwith names. Any integer can be cast to it, and the compiler knows it:The TypeScript version gets away without one only because its declarednumberreturn type makes the compiler check the cases. A Rustmatchis checked whether or not it produces a value.
var light = (Light)42;
Console.WriteLine(light);
Console.WriteLine(Enum.IsDefined(light));
enum Light { Red, Yellow, Green }Output
42 False
This prints 42 and False.
A Rust Light is always Red, Yellow or Green, so a match that lists all three is complete and needs no fallback.
Mental model shiftSame word, different idea
A C# enum gives names to numbers.TypeScript’s own enum gives names to numbers or strings. A Rust enum defines a type with a closed set of cases, and each case can hold different data. When you read “enum” in Rust code, think “discriminated union”, not “TypeScript enum”.“sealed record hierarchy”, not “C# enum”.
Variants that carry data
Here’s where Rust enums pull ahead. Each variant can carry its own fields, in any of the three struct forms from Structs & impl blocks: none, named, or by position.
type Message =
| { kind: "quit" }
| { kind: "move"; x: number; y: number }
| { kind: "write"; text: string };
function describe(message: Message): string {
switch (message.kind) {
case "quit":
return "quit";
case "move":
return `move to ${message.x},${message.y}`;
case "write":
return `write "${message.text}"`;
}
}
const messages: Message[] = [
{ kind: "quit" },
{ kind: "move", x: 3, y: 4 },
{ kind: "write", text: "hi" },
];
for (const message of messages) {
console.log(describe(message));
}Message[] messages = [new Quit(), new Move(3, 4), new Write("hi")];
foreach (var message in messages)
{
Console.WriteLine(Describe(message));
}
static string Describe(Message message) => message switch
{
Quit => "quit",
Move(var x, var y) => $"move to {x},{y}",
Write(var text) => $"write \"{text}\"",
_ => throw new ArgumentOutOfRangeException(nameof(message)),
};
abstract record Message;
sealed record Quit : Message;
sealed record Move(int X, int Y) : Message;
sealed record Write(string Text) : Message;enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
impl Message {
fn describe(&self) -> String {
match self {
Message::Quit => String::from("quit"),
Message::Move { x, y } => format!("move to {x},{y}"),
Message::Write(text) => format!("write \"{text}\""),
}
}
}
fn main() {
let messages = [
Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write(String::from("hi")),
];
for message in &messages {
println!("{}", message.describe());
}
}Output
quit move to 3,4 write "hi"
What’s different in the Rust version:
- The tag is built in. There’s no
kindfield to name, spell or keep in sync. Every enum value knows which variant it is. - Fields exist only inside their variant.
xandyare only reachable aftermatchhas confirmed the value is aMove. The patternMessage::Move { x, y }checks the variant and pulls out its fields in one step, like TypeScript narrowing onkind, like the positional patternMove(var x, var y)in C#. - The set of variants is closed. Nobody can add a fourth
Messagevariant from outside the enum, so the compiler knows when amatchis complete. C# can’t know that: other code can derive another record fromMessage, so the compiler warns until you add_ => throw.A TypeScript union is closed too, but the compiler only checks aswitchagainst it when a declared return type or anevercheck forces it.
Caught at compile timeInvalid states don't compile
In TypeScript, a { kind: "move", text: "hi" } is a type error, but JSON.parse can still hand you one at run time.In C#, a Message variable can be null, or a subclass you didn’t expect. A Rust Message is always exactly one of its variants, with exactly that variant’s fields.
The compiler checks every match
A match must handle every variant. Add a variant to the enum, and every match that doesn’t handle it stops compiling, with an error that lists the missing pattern:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
Clear, // new variant
}
impl Message {
fn describe(&self) -> String {
match self {
Message::Quit => String::from("quit"),
Message::Move { x, y } => format!("move to {x},{y}"),
Message::Write(text) => format!("write \"{text}\""),
}
}
}Rust doesn't compile this: error E0004
error[E0004]: non-exhaustive patterns: `&Message::Clear` not covered
--> main.rs:10:15
|
10 | match self {
| ^^^^ pattern `&Message::Clear` not covered
|
note: `Message` defined here
--> main.rs:1:6
|
1 | enum Message {
| ^^^^^^^
...
5 | Clear, // new variant
| ----- not covered
= note: the matched value is of type `&Message`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
13 ~ Message::Write(text) => format!("write \"{text}\""),
14 ~ &Message::Clear => todo!(),
|const unreachable: never = message check in a default case.switch over a record hierarchy has the _ arm anyway (without it, the compiler warns, CS8509), so the new case compiles fine and lands in the throw at run time.Idiomatic RustAvoid _ on your own enums
A _ => ... arm matches anything, including variants added next year. Spell out every variant instead, so adding one shows you every match to update. Keep _ for types with too many values to list, such as numbers and strings. Exhaustive match & destructuring covers patterns, guards and bindings in depth.
Option is just an enum
Rust has no null. A value that may be missing has type Option<T>, and Option is an ordinary enum from the standard library, defined roughly like this:
enum Option<T> {
None,
Some(T),
}You use it with the same match as any other enum. The compiler won’t let you use the String inside until you’ve handled None:
fn find_user(id: u32) -> Option<String> {
if id == 1 {
Some(String::from("Ada"))
} else {
None
}
}
fn main() {
for id in [1, 2] {
match find_user(id) {
Some(name) => println!("found {name}"),
None => println!("no user {id}"),
}
}
}Option is so common that it’s always in scope: you write Some and None without Option::. Module 6 covers it in depth, with the helper methods that replace ?. and ??.
Which one should I use?
When you model data, the question is whether a value has all of some fields, or is one of several cases.
| What | When | Why | How |
|---|---|---|---|
| C-like enum | A value is one of a fixed set of names with no extra data: a status, a direction, a log level. | Unlike a C# enum, no other value can sneak inNo other value can sneak in, even at run time, so match needs no fallback. | enum Light { Red, Yellow, Green }. If you need the number, Light::Green as u8 gives 2. |
| Enum with data | A value is one of several cases, and each case has its own fields: events, commands, messages, parse results. | Each case’s fields only exist in that case, and the compiler checks that every match handles every case. | enum Message { Quit, Move { x: i32, y: i32 } }, handled with match. |
| Struct | A value always has all of its fields: a user, a config, a point. | Fields are always there, so you read them directly, with no match. | struct Point { x: i32, y: i32 }, read as point.x. |
Option<T> | A value that may be missing: a lookup, an optional field. | It’s the standard “something or nothing” enum, and the whole ecosystem uses it. Don’t write your own. | Option<String>, built with Some(name) or None. Module 6 covers it. |
Rule of thumb: if you’d describe it with “and”, use a struct. If you’d say “or”, use an enum. When every case shares some fields, combine them: a struct for the shared fields with an enum field for the part that varies, such as struct Order { id: u32, status: Status }.
Under the hood
An enum value is stored inline, like a struct. It holds a small number, the tag (also called the discriminant), that says which variant it is, followed by room for the largest variant’s fields. So its size is the largest variant plus the tag, rounded up for alignment. Nothing goes on the heap unless a variant’s fields own heap data, like the String in Message::Write.
Rust doesn’t promise an exact layout for enums, so the sizes below are what today’s compiler produces on a 64-bit target, not rules to rely on. The last line is the exception: Option<&u32> is guaranteed to be the same size as &u32 (see the niche optimization below).
enum Light {
Red,
Yellow,
Green,
}
enum Shape {
Square(u32),
Rectangle { width: u32, height: u32 },
}
assert_eq!(size_of::<Light>(), 1); // just the tag
assert_eq!(size_of::<Shape>(), 12); // a 4-byte tag (today) plus the largest variant (8)
assert_eq!(size_of::<Option<u32>>(), 8); // a 4-byte tag (today) plus the u32
assert_eq!(size_of::<Option<&u32>>(), 8); // no tag at all: None is the null pointerCompare that with TypeScriptC#. A TypeScript discriminated union is a heap object with a kind string property.A C# record hierarchy is a heap object per value, reached through a reference. A Rust enum is a plain value: an array of Shapes is one block of 12-byte slots, with no pointers to follow.
The last line of the example is the niche optimization. A reference can never be null, so Rust uses the null pointer to mean None, and Option<&u32> is the same size as &u32. Rust guarantees this for references and Box, so Option costs nothing there. C#‘s int? (a Nullable<int>) needs a separate HasValue flag next to the number, much like Option<u32> above.
Here are the two Options from the example, byte by byte:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Size |
|---|---|---|---|---|---|---|---|---|---|
Option<u32>: Some(7) | tag: Some4 bytes | 7: u324 bytes | 8 bytes | ||||||
Option<u32>: None | tag: None4 bytes | unused4 bytes | 8 bytes | ||||||
Option<&u32>: Some | address, never 08 bytes · pointer | 8 bytes | |||||||
Option<&u32>: None | 0 (null): None8 bytes · pointer | 8 bytes | |||||||
Four values, 8 bytes each. Option<u32>, today on a 64-bit target: Some(7) is a 4-byte tag saying Some, followed by the 4-byte u32. None is the tag saying None, followed by 4 unused bytes. Option<&u32> has no tag at all: Some is just the 8-byte address, which is never 0, and None is the same 8 bytes holding 0, the null pointer. That layout is guaranteed.
Common pitfalls
Common pitfallComparing with == needs PartialEq
In TypeScript, light === "red" just works.In C#, light == Light.Red just works. A Rust enum doesn’t support == until you ask for it:
enum Light {
Red,
Yellow,
Green,
}
let light = Light::Red;
if light == Light::Red {
println!("stop");
}Rust doesn't compile this: error E0369
error[E0369]: binary operation `==` cannot be applied to type `Light`
--> main.rs:8:10
|
8 | if light == Light::Red {
| ----- ^^ ---------- Light
| |
| Light
|
note: an implementation of `PartialEq` might be missing for `Light`
--> main.rs:1:1
|
1 | enum Light {
| ^^^^^^^^^^ must implement `PartialEq`
help: consider annotating `Light` with `#[derive(PartialEq)]`
|
1 + #[derive(PartialEq)]
2 | enum Light {
|Add #[derive(PartialEq)] above the enum, or check one variant with matches!(light, Light::Red), which works without it. For anything more than one variant, use match.
Common pitfallA variant is not a type
In C#, Move is a class of its own.In TypeScript, you can narrow to one member of a union and pass it around. In Rust, Message::Move is a variant, not a type, so a function can’t take one:
fn area(rect: Shape::Rectangle) -> u32 {
rect.width * rect.height
}Rust doesn't compile this: error E0573
error[E0573]: expected type, found variant `Shape::Rectangle`
--> main.rs:1:15
|
1 | fn area(rect: Shape::Rectangle) -> u32 {
| ^^^^^^^^^^^^^^^^ not a typeIf a case needs to be passed around on its own, give it a struct and wrap it: struct Rectangle { width: u32, height: u32 } and enum Shape { Square(u32), Rectangle(Rectangle) }. Then a function can take a Rectangle.
Common pitfallA number doesn't turn into an enum
C# casts in both directions. Rust casts a C-like enum to a number with as, but not back, because not every number is a valid variant:
enum Light {
Red,
Yellow,
Green,
}
let code = Light::Green as u8; // fine: 2
let light = 2 as Light;Rust doesn't compile this: error E0605
error[E0605]: non-primitive cast: `i32` as `Light` --> main.rs:8:13 | 8 | let light = 2 as Light; | ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
Write a function that matches on the number and returns an Option<Light>, so the caller has to handle a number with no matching light. The TryFrom trait, from Module 9, is the standard home for that conversion.
Try it yourself
Exercise: port this to Rust
Port this to a Rust enum with a label method.
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; cents: number };
function label(payment: Payment): string {
switch (payment.kind) {
case "cash":
return "cash";
case "card":
return `card ending ${payment.last4}`;
case "voucher":
return `voucher worth ${payment.cents} cents`;
}
}
const payments: Payment[] = [
{ kind: "cash" },
{ kind: "card", last4: "4242" },
{ kind: "voucher", cents: 500 },
];
for (const payment of payments) {
console.log(label(payment));
}Payment[] payments = [new Cash(), new Card("4242"), new Voucher(500)];
foreach (var payment in payments)
{
Console.WriteLine(Label(payment));
}
static string Label(Payment payment) => payment switch
{
Cash => "cash",
Card(var last4) => $"card ending {last4}",
Voucher(var cents) => $"voucher worth {cents} cents",
_ => throw new ArgumentOutOfRangeException(nameof(payment)),
};
abstract record Payment;
sealed record Cash : Payment;
sealed record Card(string Last4) : Payment;
sealed record Voucher(int Cents) : Payment;Expected output
cash card ending 4242 voucher worth 500 cents
Show a hint
Make Payment an enum with three variants: a unit variant for cash, a variant with a named last4 field for a card, and a tuple variant holding the cents for a voucher. Then match on self in a label method.
Show a solution
enum Payment {
Cash,
Card { last4: String },
Voucher(u32),
}
impl Payment {
fn label(&self) -> String {
match self {
Payment::Cash => String::from("cash"),
Payment::Card { last4 } => format!("card ending {last4}"),
Payment::Voucher(cents) => format!("voucher worth {cents} cents"),
}
}
}
fn main() {
let payments = [
Payment::Cash,
Payment::Card {
last4: String::from("4242"),
},
Payment::Voucher(500),
];
for payment in &payments {
println!("{}", payment.label());
}
}The kind tag becomes the variant itself, so there is no kind field. Each variant holds only its own data, and match pulls it out. There is no default arm: if you add a fourth payment type later, label stops compiling until you handle it.
Saved in this browser only.