Enums & Algebraic Data Types
Wyn enums are algebraic data types - each variant can carry different data.
Simple Enums
wyn
enum Color { Red, Green, Blue }
fn main() -> int {
c = Color.Red
match c {
Color.Red => print("red")
Color.Green => print("green")
Color.Blue => print("blue")
}
return 0
}Enum to String
Call .to_string() on any enum value to get the variant name:
wyn
enum Direction { North, South, East, West }
print(Direction.North.to_string()) // "North"
d = Direction.East
print(d.to_string()) // "East"Enums with Data
Each variant can carry a value:
wyn
enum Shape {
Circle(float)
Square(float)
Rectangle(float)
}
fn area(s: Shape) -> float {
return match s {
Shape.Circle(r) => 3.14159 * r * r
Shape.Square(side) => side * side
Shape.Rectangle(w) => w * 2.0
}
}
fn main() -> int {
c = Shape.Circle(5.0)
print("Area: ${area(c)}")
return 0
}Returning Enums from Functions
wyn
enum Result {
Ok(string)
Err(string)
}
fn divide(a: int, b: int) -> Result {
if b == 0 { return Result.Err("division by zero") }
return Result.Ok("${a / b}")
}
fn main() -> int {
r = divide(10, 3)
match r {
Result.Ok(val) => print("Result: ${val}")
Result.Err(msg) => print("Error: ${msg}")
}
return 0
}Pattern Matching
Match expressions return values:
wyn
fn describe(n: int) -> string {
return match n {
0 => "zero"
1 => "one"
_ if n < 0 => "negative"
_ if n > 100 => "big"
_ => "other"
}
}Match on Strings
wyn
fn greet(lang: string) -> string {
return match lang {
"en" => "Hello"
"es" => "Hola"
"fr" => "Bonjour"
_ => "Hi"
}
}See Also
- Pattern Matching - destructure enum variants
- Error Handling - Result and Option are enums
- Structs - custom data types with fields