Skip to content
ghaerdi edited this page Aug 14, 2026 · 2 revisions

match

Import match and P from @ghaerdi/rustify/match.

Matching

  • match(value): Starts a match chain, returning a Match you extend with .with() cases and terminate with .exhaustive(), .otherwise() or .run().
  • matches(value, pattern): Standalone predicate — returns true if value matches pattern.

Terminals

  • .with(pattern, handler): Adds a case. handler receives the value narrowed to what pattern matches. Returns the extended match.
  • .exhaustive(): Runs the match and throws if nothing matched. At compile time, calling it on an incomplete match is a type error at the call site that names the missing cases (e.g. NeverCase<"NonExhaustive: unhandled case { type: rect }">).
  • .otherwise(handler): Runs the match, calling handler(value) for anything no case matched.
  • .run(): Runs the match, returning undefined if nothing matched — excluded from the return type when every case is covered.

Option/Result patterns

Option.some, Option.none, Result.ok and Result.err match the respective variant and pass the unwrapped value (or error) to the handler — n below is number, not Option<number>:

match(opt)
  .with(Option.some, (n) => n.toFixed(2))
  .with(Option.none, () => "none")
  .exhaustive();

These patterns are per-variant: .with(Option.some, ...).exhaustive() alone is a compile error naming the missing variant (NeverCase<"NonExhaustive: unhandled case { __tag: none }">).

Patterns (the P namespace)

  • P.any / P._: Matches anything (catch-all).
  • P.string, P.number, P.boolean, P.bigint, P.symbol: Matches primitive types.
  • P.nullish: Matches null or undefined.
  • P.array(pattern?): Matches arrays; optionally checks every element.
  • P.instanceOf(Ctor): Matches class instances.
  • P.union(...patterns): Matches any of the given patterns.
  • P.when(guard): Matches when the type guard returns true.
  • P.not(pattern): Matches everything except pattern.
  • P.optional(pattern): Matches undefined or pattern.

Types

  • Match: the chain type returned by match().
  • Pattern<TInput>: a valid pattern for TInput.
  • Narrow<TInput, P>: the type of a value matched by pattern P.

See Also

Clone this wiki locally