Lyricdev
GitHub

LYR-SEM0097

a name bound twice in one pattern

error ยท spec 09-patterns

One pattern binds the same name in two places, such as .Rect { w = n, h = n } or E.B(x, x).

Explanation

A name binds once in a pattern; a second binding could only replace or drop the first, and either would be silent. Or-pattern alternatives are separate and may, and must, bind the same names. Shadowing a name from outside the pattern stays allowed.

Bind distinct names, and compare them in a guard if the two values must be equal.

Wrong

enum Shape {
    Rect { w: int, h: int },
    Empty,
}

fn area(s: Shape): int {
    return match (s) { .Rect { w = n, h = n } => n * n, .Empty => 0 };
}

fn main(): void {
    let _ = area(Shape.Empty);
}
enum Shape {
    Rect { w: int, h: int },
    Empty,
}

fn area(s: Shape): int {
    return match (s) { .Rect { w = a, h = b } => a * b, .Empty => 0 };
}

fn main(): void {
    let _ = area(Shape.Empty);
}