Range types
- Rust course
- Beginner
- Lesson 58/115
- 4 min
Learn the Range and RangeInclusive types.
Range types
1..4 is a Range<i32>, 1..=4 a RangeInclusive<i32> value. Besides slicing, ranges are also used in loops and as iterators:
let r = 1..=5;
println!("{}", r.contains(&5)); // true
for i in (1..4).rev() { print!("{i} "); } // 3 2 1
let tek: Vec<i32> = (1..10).step_by(2).collect(); // [1, 3, 5, 7, 9]Char and empty ranges
Ranges work with chars too: ('a'..='e').collect::<String>() → "abcde". If the start is equal to or greater than the end, the range is empty: (5..5).count() gives 0, and so does (5..1).count(); counting down needs rev().
let harfler: String = ('a'..='e').collect();
println!("{harfler} {}", (5..1).count()); // abcde 0Practice Range operations
Print, on one line, the sum of the elements of (1..=10).step_by(3) (sum::<i32>()) and the vector made from (1..5).rev() (collect::<Vec<i32>>()).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let t: i32 = (1..=10).step_by(3).sum();
let v: Vec<i32> = (1..5).rev().collect();
println!("{} {:?}", t, v);
}Expected output
22 [4, 3, 2, 1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>(0..10).step_by(4).collect::<Vec<_>>()</code>?
- [0, 4, 8, 12]
- [0, 4]
- [0, 4, 8] Correct answer
- [4, 8]
Explanation: step_by starts with the first element and skips by 4; 10 is not included.
2 Count down
for i in (1..=3).____() {
print!("{i} "); // 3 2 1
}
for i in (1..=3).rev() {
print!("{i} "); // 3 2 1
}
Explanation: rev walks the iterator in reverse.
3 Range and element count
| Term | Meaning |
|---|---|
1..4 |
3 |
1..=4 |
4 |
5..5 |
0 |
(0..10).step_by(4) |
3 elements |