# Pattern Matching -- Advanced Patterns

Examples without `fn main` are independent fragments; application-specific
functions such as `compute` and `process` stand for your own code.

This page covers pattern matching features beyond the basics: `if let`, `while let`, match guards, or-patterns, rest patterns, and destructuring in `let` bindings.

## `if let` -- Conditional Single-Pattern Match

`if let` tests a value against a single pattern and executes the block only if it matches. It is syntactic sugar for a `match` with one arm and a wildcard.

```vex
let opt: Option<i32> = Some(42)

// if let: concise single-pattern match
if let Some(value) = opt {
    $println(f"Got value: {value}")
}

// Equivalent match (more verbose)
match opt {
    Some(value) => $println(f"Got value: {value}"),
    None => {},
}
```

### `if let` with Multiple Conditions

Test an additional condition inside the successful pattern branch:

```vex
let data: Result<i32, string> = fetchData()

if let Ok(value) = data {
    if value > 0 { $println(f"Positive result: {value}") }
}
```

### `if let` with Struct Patterns

```vex
struct Point {
    public:
    x: f64,
    y: f64,
}

let maybe_point: Option<Point> = Some(Point { x: 3.0, y: 4.0 })

if let Some(Point { x, y }) = maybe_point {
    $println(f"Point at ({x}, {y})")
}
```

### `if let` with `else`

```vex
let result = compute()

if let Ok(data) = result {
    process(data)
} else {
    $println("Computation failed")
}
```

## `while let` -- Loop While Pattern Matches

`while let` repeatedly tests a value against a pattern, continuing as long as it matches:

```vex
let! stack = Vec.new<i32>()
stack.push(1)
stack.push(2)
stack.push(3)

// pop removes the final element: this is a stack.
while let Some(item) = stack.pop() {
    $println(f"Processing: {item}")
}
// Output: Processing: 3, Processing: 2, Processing: 1
```

### Iterator Pattern with `while let`

```vex
let! iter = someCollection.iter()

while let Some(element) = iter.next() {
    process(element)
}
```

### Draining Available Channel Messages

```vex
while let Some(msg) = channel.tryRecv() {
    handleMessage(msg)
}
```

`tryRecv` is nonblocking. This loop stops when no message is immediately
available; it does not wait for future messages or prove that producers have
finished. See [Channels](../concurrency/channels.md) for blocking receive and
closure behavior.

## Match Guards -- Conditional Patterns

Match guards add a boolean condition after a pattern using `if`:

```vex
let number = 15

let description = match number {
    n if n < 0 => "negative",
    n if n == 0 => "zero",
    n if n < 10 => "single digit",
    n if n % 2 == 0 => "even",
    n => "odd",
}
// description = "odd"
```

### Guards with Enum Patterns

```vex
fn processResult(res: Result<i32, string>): string {
    return match res {
        Ok(v) if v > 100 => "large success",
        Ok(v) if v > 0 => "small success",
        Ok(v) => "zero or negative",
        Err(e) if e.startsWith("NET_") => f"Network error: {e}",
        Err(e) => f"Other error: {e}",
    }
}
```

### Guards with Destructured Patterns

```vex
struct Person {
    public:
    name: string,
    age: i32,
}

fn canDrink(person: Person): bool {
    return match person {
        Person { age, .. } if age >= 21 => true,
        _ => false,
    }
}
```

### Bindings in guarded alternatives

Every alternative must provide the bindings the arm uses. For example,
`Some(n) | None if n > 0` is invalid because `None` does not bind `n`.
Use separate arms for these different shapes:

```vex
fn positive(value: Option<i32>): bool {
    return match value {
        Some(n) if n > 0 => true,
        Some(_) => false,
        None => false,
    };
}
```

## Or-Patterns -- Multiple Patterns, One Arm

Use `|` to match multiple patterns with the same handler:

```vex
let x = 2

let kind = match x {
    1 | 2 | 3 => "small",
    4 | 5 | 6 => "medium",
    _ => "large",
}
```

### Or-Patterns with Enums

```vex
fn isClientError(res: Result<i32, HttpError>): bool {
    return match res {
        Err(BadRequest) | Err(Unauthorized) | Err(Forbidden) | Err(NotFound) => true,
        _ => false,
    }
}
```

### Matching Different Shapes

```vex [areas.vx]
enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
    Triangle(f64, f64, f64),
}
fn area(shape: Shape): f64 {
    return match shape {
        Shape.Circle(r) => 3.14159 * r * r,
        Shape.Rectangle(w, h) => w * h,
        Shape.Triangle(a, b, c) => {
            let s = (a + b + c) / 2.0;
            Math.sqrt(s * (s - a) * (s - b) * (s - c))
        },
    };
}
fn main(): i32 {
    let circle = area(Shape.Circle(2.0));
    let square = area(Shape.Rectangle(2.0, 2.0));
    let rectangle = area(Shape.Rectangle(2.0, 3.0));
    let triangle = area(Shape.Triangle(3.0, 4.0, 5.0));
    if circle < 12.56635 || circle > 12.56637 { return 1; }
    if square != 4.0 || rectangle != 6.0 || triangle != 6.0 { return 1; }
    $println("areas ok");
    return 0;
}
```

This fixture assumes non-negative circle and rectangle dimensions and valid triangle sides; it does not validate inputs. The circle uses an approximation of π, so its check uses a tolerance. The expected output is `areas ok`, with exit status 0.

## Rest Patterns -- Ignoring Remaining Fields

The `..` pattern ignores remaining fields or elements:

### In Struct Patterns

```vex
struct Config {
    public:
    host: string,
    port: i32,
    timeout: i32,
    retries: i32,
    verbose: bool,
}

let cfg = Config { host: "localhost", port: 8080, timeout: 5000, retries: 3, verbose: true }

// Only extract what you need
let Config { host, port, .. } = cfg
// host = "localhost", port = 8080, rest is ignored
```

### In Tuple Patterns

Spell the tuple shape explicitly and use `_` for each ignored position:

```vex
let triple = (1, 2, 3)
let (first, _, last) = triple
// first = 1, last = 3
```

### In Array Patterns

Array rest patterns are terminal. `..` ignores the remaining elements;
`...rest` binds them. A suffix after the rest, such as `[first, .., last]`,
is not accepted.

```vex
let numbers = [10, 20, 30, 40, 50]
let [head, ..] = numbers
let [first, second, ...rest] = numbers
// head = first = 10; second = 20; rest contains 30, 40, 50.
```

Use a pattern whose fixed prefix fits the array. Matching a fixed-size array
against an empty-array pattern does not make it a variable-length collection.

## Destructuring in `let` Bindings

Beyond `match`, patterns work directly in `let` statements:

### Struct Destructuring

```vex
struct Point {
    public:
    x: f64,
    y: f64,
}

let p = Point { x: 3.0, y: 4.0 }

// Destructure into individual variables
let Point { x, y } = p
// x = 3.0, y = 4.0

// Rename fields during destructuring
let Point { x: px, y: py } = p
// px = 3.0, py = 4.0
```

### Tuple Destructuring

```vex
let pair = (42, "hello")
let (num, text) = pair
// num = 42, text = "hello"
```

### Array Destructuring

```vex
let rgb = [255u8, 128u8, 64u8]
let [r, g, b] = rgb
// r = 255, g = 128, b = 64
```

### Enum variants and early return

A variant can fail to match, so handle that branch explicitly with `match`
or `if let`. The documented `let` destructuring forms are tuples, structs,
and arrays; use the following early-return pattern for an `Option`:

```vex
fn incrementPresent(value: Option<i32>): Option<i32> {
    let inner = match value {
        Some(inner) => inner,
        None => return None,
    };
    return Some(inner + 1);
}
```

This keeps `inner` available after the match and makes the unsuccessful path
visible. It does not require `let Some(...) = ... else` syntax.

## Pattern Matching on References

When matching through references, Vex automatically dereferences:

```vex
fn describe(opt: &Option<i32>): string {
    return match opt {
        Some(v) => f"Value: {v}",  // v is &i32, auto-derefed
        None => "Nothing",
    }
}
```

## Best Practices

1. Use `if let` when you only care about one pattern and want to ignore all others.
2. Use `while let` for consuming iterators or processing queues until exhaustion.
3. Use guards (`if` in match arm) instead of complex nested matches.
4. Use `|` (or-patterns) to avoid code duplication when multiple patterns share the same handler.
5. Use `..` (rest pattern) to extract only the fields you need from large structs; use terminal array rest patterns for arrays.
6. Prefer `let` destructuring for fixed-shape data (tuples, known struct fields).
7. Use `match` when you need exhaustiveness checking -- the compiler ensures all cases are covered.
8. Use explicit `match` and early `return` when a variant mismatch must stop the function.

## Related Pages

- [Pattern Matching](pattern-matching.md) -- basic patterns
- [Enums](enums.md) -- enum variant patterns
- [Structs](structs.md) -- struct destructuring
