Enums and Match
Enums in Zynx define a closed set of named variants. Variants can optionally carry data and integrate tightly with the match expression for exhaustive, pattern-based control flow.
This section covers:
- how to declare enums,
- how to construct values,
- how to use
matchfor branching, and - how to work with generic enums.
For an overview of types and control flow, see:
Definition
enum Shape {
Circle(radius: f32),
Rect(w: f32, h: f32),
Point,
}
Construction
Construct a variant using the Enum.Variant name and field initializers.
let c = Shape.Circle { radius: 10.0 };
let p = Shape.Point {};
Matching
Use match to branch on enum variants. Patterns bind fields by position.
let area = match c {
.Circle(r) => r * r * 3.14,
.Rect(w, h) => w * h,
.Point => 0.0,
};
Advanced Patterns
- Wildcards: Use
_to match any remaining variants. - Ignoring Data: Use
.Variant(_)to ignore data fields.
match r {
.Rect(_) => 1,
_ => 0,
};
Generics
Enums can be generic, allowing them to wrap any type.
enum Option<T> {
Some(val: T),
None,
}
let opt = Option<i32>.Some { val: 42 };
Generic enums are commonly used for:
- optional values (for example,
Option<T>), - result types that distinguish success and failure,
- tagged unions for protocol or message handling.
See also
- Type System – overview of custom types, including enums and error unions.
- Control Flow – how
matchfits into the broader control flow model. - Error Handling – error sets and error unions (
T!), which often pair with enums.