Expressions & Flow · 10 min · free with an account

Ranges

Lesson preview · about 30%

Range syntax makes boundaries visible instead of hiding an off-by-one rule.

Core idea

a..b excludes b; a..=b includes b.

Start with the idea

The range 0..3 contains 0, 1, and 2; its upper bound is excluded. The inclusive form 1..=3 also contains 3. Half-open ranges fit indexing because a length can be used directly as the excluded end. Inclusive ranges are useful when both endpoints belong to the domain.

Half-open ranges make boundaries compose cleanly. In 0..3, the first value is included and 3 is excluded, so there are exactly three integers. This mirrors a slice whose length is 3: valid positions are 0, 1, and 2, while the length itself is the first position after the slice. Two adjacent spans such as 0..3 and 3..6 meet without overlapping. That is why half-open intervals are common in indexing and iteration.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics