New Issue: Create a pattern matching syntax for unions

28625, "jabraham17", "Create a pattern matching syntax for unions", "2026-03-31T21:41:00Z"

While working on Expand and improve support for union by jabraham17 · Pull Request #28601 · chapel-lang/chapel · GitHub, I created some nicer syntax for unions

union U {
  var x: int;
  var y: real;
}
var u: U;
select u {
  when U.x {
    writeln("x is ", u.x);
  }
  when U.y {
    writeln("y is ", u.y);
  }
}

This gets us really nice to a pattern matching syntax for Chapel (at least for unions), but its not perfect.
A few issues

  • The when clauses are not enforced by the compiler, I can write whatever expression I want in when, I just happen to use nice syntax of U.x
  • I still have to use u.x to access the field in the when block.

It would be really nice to have the compiler introduce a temporary for me that auto-accesses the field, avoiding overhead and reducing the chance for mistakes

For example, what if I could write the following

select u {
  when var myX = x  {
    writeln("x is ", myX);
  }
  when y  {
    writeln("y is ", y);
  }
}

In the first when, I am pattern matching that the x field is active and getting the value of x into a temporary variable named myX. In the second, I am pattern matching y is active and getting the value of y into a temporary variable named y.

This is an even nicer ergonomic improvement over the current union pattern matching. It could be further improved if we make bad union accesses throw (see Should unions throw or halt? · Issue #28624 · chapel-lang/chapel · GitHub), such that the pattern match avoids the throwing check. I see these two features as working hand in hand

See [Feature Request]: extensions to select syntax for go-style channels and sockets · Issue #26993 · chapel-lang/chapel · GitHub for similar ideas with sockets