Files
mist-website/content/docs/components/enums.mdx
T
2026-06-28 22:45:01 +02:00

88 lines
2.0 KiB
Plaintext

---
title: Enums
description: Defining algebraic data types with Mist's type-first convention.
icon: Layers
---
Enums in Mist serve as powerful algebraic data types (ADTs), maintaining the exact behavior and safety of Rust enums while using parentheses for tuple variants and `Type name` for struct-like fields.
## Basic Syntax
An enum can contain unit variants, tuple variants (with types in parentheses), or struct-like variants.
```mist
pub enum TaskState {
Pending,
InProgress,
Completed,
Failed {
String reason,
i32 code,
},
}
```
## Variant Types
Mist supports all standard variant shapes:
```mist
enum OptionInt {
None, // Unit
Some(i32), // Tuple (parentheses)
}
enum Shape {
Circle { i32 radius }, // Struct-like
Rect { i32 w, i32 h },
}
```
### Instantiation & Matching
Tuple variants are created and matched with parentheses:
```mist
let x = OptionInt::Some(42);
match x {
OptionInt::None => { println!("none"); }
OptionInt::Some(v) => { println!("{}", v); }
}
```
Struct variants use brace notation:
```mist
let c = Shape::Circle {
radius: 5,
};
match c {
Shape::Circle { radius } => { println!("{}", radius); }
Shape::Rect { .. } => { /* ignore */ }
}
```
## Generics
Enums declare generics and lifetimes in angle brackets after the name.
```mist
pub enum Validation<'a, T> {
Valid(T),
Invalid {
&'a str message,
u32 error_id,
},
}
```
## Key Characteristics
- **Consistent Declaration**: Struct-like variants use `Type name` order, consistent with Mist structs.
- **Parentheses Tuples**: Tuple variants use `()` syntax, consistent with Rust.
- **Rust-Native ADTs**: Enums compile directly to Rust enums, allowing exhaustive pattern matching and zero-cost abstraction.
- **Shared Visibility**: The `pub` modifier at the enum level exports all variants.
- **Comma-Separated Members**: Fields within struct-like variants are separated by commas.