🎯 Pattern Matching (match)
match to zaawansowane dopasowywanie wzorców z destructuringiem.
Podstawowe użycie
let result = match value {
0 -> "zero",
1 -> "one",
_ -> "other"
};
Destructuring obiektów
let point = {x: 10, y: 20};
let result = match point {
{x, y} -> `Point at ${x}, ${y}`,
_ -> "Unknown"
};
print(result);
Destructuring list
let coords = [3, 4];
let desc = match coords {
[a, b] -> `2D: ${a}, ${b}`,
[a, b, c] -> "3D point",
_ -> "Unknown"
};
Match z guard (warunkiem)
let value = 42;
let category = match value {
n if n < 0 -> "negative",
n if n == 0 -> "zero",
n if n < 100 -> "medium",
_ -> "large"
};
print(category);
Praktyczne przykłady
fn area(shape) {
return match shape {
{type: "circle", radius: r} -> PI * r * r,
{type: "rectangle", width: w, height: h} -> w * h,
{type: "square", side: s} -> s * s,
_ -> 0
};
}
print(area({type: "circle", radius: 5}));
print(area({type: "rectangle", width: 4, height: 3}));