Skip to main content

Pattern Matching

Pattern matching allows you to check values against patterns and destructure data. Here's how different languages handle pattern matching.

Basic Pattern Matching​

// Switch statement
switch (value) {
case 1:
console.log("one");
break;
case 2:
case 3:
console.log("two or three");
break;
default:
console.log("other");
}

// Destructuring (object)
const { name, age } = person;
const { name: userName, ...rest } = person;

// Destructuring (array)
const [first, second, ...remaining] = arr;
const [a, , c] = [1, 2, 3]; // skip second

// Nested destructuring
const { address: { city } } = person;

// Default values
const { name = "unknown" } = person;

Key Takeaways​

  • Exhaustive matching -- Rust and Swift require match/switch to cover all cases, preventing bugs from missed branches; other languages use default/else as catch-alls.
  • Destructuring support -- Rust, Swift, Python, and C# offer rich destructuring of structs, tuples, and enums; C and Go have minimal or no destructuring.
  • Guard clauses -- Rust (if), Swift (where), Python (if), Java 21+ (when), and C# support pattern guards for conditional logic within match arms.
  • Algebraic data types -- Rust and Swift enums with associated values enable pattern matching on data-carrying variants; Zig's tagged unions offer similar capabilities.