Integer ranges
Ranges come in different flavors, depending on what kind of bounds they have. For example 0..3
(Range) is a range
that contains numbers 0, 1 and 2, 0..=3
(RangeInclusive) is a range that contains numbers 0, 1, 2 and 3.
The most common use of ranges is in for
loops and in slice indexing.
for _ in 0..3 {
// loop body
}
Run this example
let hw = "hello world";
println!("{}", hw[..5]); // prints "hello"
println!("{}", hw[6..]); // prints "world"
Run this example
There are also some other places where ranges are used in the standard library (e.g. next for generating random numbers).
See also Range and RangeOf for protocols that can be used for designing APIs that accept generic ranges.
Structs
An unbounded range (
..
)
A range with a lower bound (
a..
)
A range with an upper bound (
..a
)
A range with an inclusive upper bound (
..=a
)
A range with both lower and upper bounds (
a..b
)
A inclusive range with both lower and upper bounds (
a..=b
)