Skip to content

Enums & Pattern Matching

Enums in Wysna are sum types (algebraic data types / tagged unions). They allow you to represent values that can be one of several discrete variants.

A basic enum enumerates distinct variants:

enum ConnectionState {
Disconnected
Connecting
Connected
Suspended
}

Wysna provides the match expression for branching based on enum variants. The compiler strictly verifies that all possibilities are handled (exhaustiveness checking):

fn describe_state(state: ConnectionState) -> str {
return match state {
ConnectionState.Disconnected => "Socket is closed"
ConnectionState.Connecting => "Performing handshake..."
ConnectionState.Connected => "Live streaming data"
ConnectionState.Suspended => "Connection on hold"
}
}

If you omit any variant from the match block, the compiler rejects the code at compile-time:

Error: Non-exhaustive match. Missing variant: `ConnectionState.Suspended`

Enum variants can also hold data, turning them into powerful tagged unions:

enum ServerMessage {
Ping
Text(str)
Data(list[int])
Disconnect(int, str)
}
fn handle_message(msg: ServerMessage) -> unit {
match msg {
ServerMessage.Ping => {
print("Received heartbeat ping")
}
ServerMessage.Text(content) => {
print("Received text:", content)
}
ServerMessage.Data(payload) => {
print("Received binary payload of length:", len(payload))
}
ServerMessage.Disconnect(code, reason) => {
print("Connection closed. Code:", code, "Reason:", reason)
}
}
}
fn main() -> unit {
let msg1 = ServerMessage.Text("Hello from client")
let msg2 = ServerMessage.Disconnect(1000, "Clean shutdown")
handle_message(msg1)
handle_message(msg2)
}

Pattern matching unwraps and extracts inner variables safely without risky downcasting or type inspection functions.