dart-lang / dart-lang/language

Why can't I write a guard clause for each pattern in the guard clause of pattern matching?

Open
#4,094 6 comments 0 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

In the following code, “B” is assigned to res.
This is because the guard clause is evaluated after pattern matching in line 3.

```dart
final (a, b) = (0, 0);
final res = switch(a) {
== 0 || _ when b == 1 => "A",
_ => "B",
};
```

I expected the guard clause to affect each pattern as follows.
```dart
final (a, b) = (0, 0);
final res = switch(a) {
== 0 || (_ when b == 1) => "A",
_ => "B",
};
```

Consider other languages.
In Swift, we can write guard clauses for each pattern, but in Rust and Scala, we cannot write guard clauses for each pattern.
I would like to know the background behind this kind of specification for Dart.

I am not good at English, so sorry if my writing is not clear.

Contributor guide

Open the contributing guide

Research direction

No repository file, test, or entry point is named. Begin by reading the Dart language specification sections covering switch patterns, logical-or patterns, and guards, then compare the current behavior with both examples; done means the specification's intent is explained or the requested semantics are accepted for design discussion.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.