Enums
Nyx enums are algebraic data types (ADTs): each variant can carry different data, and match expressions destructure them exhaustively. This makes it impossible to forget a case at compile time.
Code
// Enums: definición, variantes con datos, match exhaustivo
enum Shape {
Circle(int),
Square(int),
Rectangle(int, int)
}
fn area(s: Shape) -> int {
return match s {
Shape.Circle(r) => r * r * 3,
Shape.Square(l) => l * l,
Shape.Rectangle(w, h) => w * h
}
}
fn describe(s: Shape) -> String {
return match s {
Shape.Circle(r) => "circulo de radio " + int_to_string(r),
Shape.Square(l) => "cuadrado de lado " + int_to_string(l),
Shape.Rectangle(w, h) => "rectangulo " + int_to_string(w) + "x" + int_to_string(h)
}
}
fn main() -> int {
let c: Shape = Shape.Circle(5)
let sq: Shape = Shape.Square(4)
let rect: Shape = Shape.Rectangle(3, 7)
print(describe(c) + " -> area aprox " + int_to_string(area(c)))
print(describe(sq) + " -> area " + int_to_string(area(sq)))
print(describe(rect) + " -> area " + int_to_string(area(rect)))
return 0
}
Output
circulo de radio 5 -> area aprox 75 cuadrado de lado 4 -> area 16 rectangulo 3x7 -> area 21
Explanation
An enum is declared with the enum keyword followed by a name and a list of variants. Each variant can carry zero or more typed values in parentheses: Circle(int) carries one integer (the radius), Rectangle(int, int) carries two (width and height). Variants without parentheses would be simple tags.
Enum values are constructed with dot notation: Shape.Circle(5). Note that Nyx uses Shape.Circle, not Shape::Circle — the dot is the variant separator throughout the language.
The match expression destructures an enum value and binds the inner data to local names. Each arm has the form Pattern => expression. The compiler enforces exhaustiveness: if any variant is missing from a match, the program will not compile.
The area formula for the circle uses integer arithmetic (r * r * 3 as an approximation of π·r²), which is why the result is labeled "aprox". Real programs would use float and the math standard library for precise results.
Source: examples/by-example/09-enums.nx