Skip to content

Struct pattern ignores a literal field sub-pattern: Point { x: 0, y } matches any x (match and let-else) #1388

Closed

Description

@ehartford

A literal (refutable) sub-pattern on a struct field is not tested: the struct pattern matches regardless of the field's value. Tuple patterns test the same literal correctly. Silent wrong code, in both match and let ... else (§9.7 Pattern Matching, §30.6 STRUCT_PAT).

type Point { x: i32, y: i32 }
fn main:
    let p = Point { x: 1, y: 7 }
    match p:
        Point { x: 0, y } => print(f"zero {y}")
        _ => print("other")
    match p:
        { x: 0, y } => print(f"zero {y}")
        _ => print("other")
    match (1, 7):
        (0, y) => print(f"zero {y}")
        _ => print("other")

Actual (stage1 of origin/fix-1354-var-destructure-mut a7e2004, same on the seed):

zero 7
zero 7
other

Expected:

other
other
other

The same happens in let Point { x: 0, y } = p else: return -1 (returns y for x: 1). Found while building the #1373/#1382 let-else pattern matrix; the let-else fixture leaves struct literal fields out until this lands.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions