Unions
A value of one of several types.
A | Bdoes not require separately named variants; this does not imply the runtime representation has no tag.
Syntax
fn process(data: string | i32) {
// data can be either string or i32
}Union types canonicalize automatically: A | B ≡ B | A, duplicates removed.
Pattern Matching
fn printParam(param: string | i32) {
match param {
string => $println("String: " + param),
i32 => $println("Int: " + param.toString()),
}
}The compiler checks exhaustiveness — missing a variant is a compile error.
Upcasting
Values implicitly upcast into union types:
let val: string | i32 | f64 = 42; // i32 → string|i32|f64
let val2: string | i32 | f64 = "hi"; // string → string|i32|f64Memory Layout
A runtime union needs enough information to identify its active alternative. In the current LLVM lowering, the compiler uses a tag and, when needed, aligned payload storage. Tag width depends on the number of alternatives; payload size and alignment depend on the target and alternatives. The exact field representation, padding, and ABI are implementation details, not a portable promise or a C union layout. Inspect and test the compiler build and target before using a union at a foreign boundary.
The source implementation is in crates/vex-compiler/src/codegen_hir/context/types/named.rs; this description is source-based and has not independently verified every release or target.
Unions vs Enums
| Feature | Union (A | B) | Enum |
|---|---|---|
| Named variants | No | Yes |
| Payload types | Yes | Yes |
| Exhaustive check | Yes | Yes |
| Representation | Runtime tag and payload in the current lowering | Depends on enum and target; do not assume a niche optimization |
| Wrap third-party types | Alternatives can be existing types | A named variant can carry an existing type |