Structs and Enums

RUDRA has structs for grouped data and enums for a fixed set of named values.

Structs

struct Point { x: int, y: int }
fn main() -> int {
    let p = Point { x: 3, y: 4 };
    print(to_str(p.x) + "\n");
    print(to_str(p.y) + "\n");
    return 0;
}
return main();

Enums

Variants are written with a dot: Color.Green. Put a return after a match that returns from its arms.

enum Color { Red, Green, Blue }
fn name(c: Color) -> str {
    match c {
        Color.Red => { return "red"; }
        Color.Green => { return "green"; }
        Color.Blue => { return "blue"; }
    }
    return "";
}
fn main() -> int {
    print(name(Color.Green) + "\n");
    return 0;
}
return main();

This program prints green.

Enums with payloads

Variants can carry a value, which a match arm binds to a name. This program prints 75 and then 0.

enum Shape { Circle(int), Rect(int), Empty }
fn area(s: Shape) -> int {
    match s {
        Shape.Circle(r) => { return 3 * r * r; }
        Shape.Rect(w) => { return w * w; }
        Shape.Empty => { return 0; }
    }
    return 0;
}
fn main() -> int {
    print(to_str(area(Shape.Circle(5))) + "\n");
    print(to_str(area(Shape.Empty)) + "\n");
    return 0;
}
return main();

Pattern matching

A match over an enum is checked for exhaustiveness: every variant must be handled, or a wildcard pattern must cover the rest.