dart-lang / dart-lang/language

Range syntax

Open
#3,366 17 comments 16 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Related: #1066 #1660 dart-lang/sdk#42652

**EDITS:**
- Changed syntax from `..` to `...` to avoid collision with cascade syntax

---

I'm proposing a mostly complete range syntax as seen in other languages such as a Zig and Rust. The range would be inclusive on both ends.

It would be something like this:

```dart
const List items = ['foo', 'bar', 'bizz'];
final [foo, bar] = items[0...1]; // returns a list with the first two items "foo" and "bar"
```

It can also be used to create lists:
```dart
final List numbers = 1...10; // makes an inclusive list with the numbers 1-10
```

It can be used to make for loops easier:
```dart
for (final i in 1...10) {
print(i); // prints 1 though 10
}

for (final i in 10...1) { // we can even go backwards!
print(i); // prints 10 through 1
}
```

Could be used to iterate through string characters (needs work):
```dart
for (final c in 'a'...'z') {
print(c); // prints "a" through "z"
}
```
This syntax with strings would probably need some work, as commented in a related issue above, character strings could be introduced like `c'a'` and might be required here because introducing a character type would be a major breaking change if you would define a character literal with single quotes.

Switch statements/expressions:
```dart
const int value = 10;

switch (value) {
case 1...5:
print("value is between 1 and 5");
case 6...10:
print("value is between 6 and 10"); // this prints
default:
print("value is $value");
}
```

### Some other questions that need to be answered

**Should ranges always be known at compile time?**
Should we be able to do something like this:

```dart
// Imagine [start] and [end] are fetched some some data source
final int start = 0;
final int end = 5;
final List inBetween = start...end; // should this be valid?
```

Contributor guide

Open the contributing guide

Research direction

Start by reading this proposal and the related issues #1066, #1660, and dart-lang/sdk#42652. Compare the examples and open questions about syntax, compile-time requirements, strings, loops, and switch cases. Done means reaching an agreed language design and documenting the resulting range semantics; no implementation files or tests are identified here.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.