Range
The Range
type in Rust represents an interval over a continuous sequence of values, typically numbers,
but can work with any type that implements the PartialOrd
and Step
traits (like
char
for example).
Ranges are used to iterate over a series of values or to define boundaries for slices and other operations.
Ranges are most commonly used in loops and indexing operations, and Rust provides multiple forms of ranges depending on the inclusivity or exclusivity of the endpoints.
Types of Ranges
Rust provides several range types, each represented by a distinct syntax:
Range
: Exclusive Range
start..end
The Range
type represents a half-open interval [start, end)
.
It starts at start
(inclusive) and goes up to, but does not include, end
.
Example:
for i in 0..5 {
println!("{}", i); // prints 0, 1, 2, 3, 4
}
RangeInclusive
: Inclusive Range
start..=end
This range includes both the start
and end
values.
It represents a fully-closed interval [start, end]
.
Example:
for i in 0..=5 {
println!("{}", i); // prints 0, 1, 2, 3, 4, 5
}
RangeFrom
: Unbounded Range (From a start)
start..
This range starts at start
and continues indefinitely.
It is useful for slicing when you want to include everything after a certain index.
Example:
let array = [1, 2, 3, 4, 5];
let slice = &array[2..]; // takes from index 2 to the end
assert_eq!(slice, &[3, 4, 5]);
RangeTo
: Unbounded Range (Up to a point)
..end
This range starts from the beginning and ends before end
. It is exclusive,
meaning it does not include end
.
Example:
let array = [1, 2, 3, 4, 5];
let slice = &array[..3]; // takes up to (but not including) index 3
assert_eq!(slice, &[1, 2, 3]);
RangeToInclusive
: Unbounded Range (Up to and including)
..=end
This is similar to RangeTo
, but it includes the end
value as well.
Example:
let array = [1, 2, 3, 4, 5];
let slice = &array[..=3]; // takes up to and including index 3
assert_eq!(slice, &[1, 2, 3, 4]);
RangeFull
: Full Range
..
The RangeFull
type is used when referring to the entire range of a collection.
It is most often used in slicing.
Example:
let array = [1, 2, 3, 4, 5];
let slice = &array[..]; // takes the entire array
assert_eq!(slice, &[1, 2, 3, 4, 5]);
Traits and Methods
Iterator
Trait
All finite ranges implement the Iterator
trait, making it easy to loop over them.
Example:
let sum: i32 = (1..5).sum(); // sums 1, 2, 3, 4
assert_eq!(sum, 10);
contains
Method
You can use the contains
method to check whether a value is within a range.
Example:
let range = 1..5;
assert!(range.contains(&3)); // true
assert!(!range.contains(&5)); // false (because it's exclusive)