Skip to content

Ranges

Build a range using the .. and ..= operators, typically for looping or indexing.

See range operators

A Range covers start to end, excluding end.

pub struct Range<T> {
pub start: T,
pub end: T,
}
for i in 0..5 {
fmt.Println(i)0 through 4, excluding 5
}

A RangeInclusive covers start to end, including end.

pub struct RangeInclusive<T> {
pub start: T,
pub end: T,
}
for i in 0..=5 {
fmt.Println(i)0 through 5, including 5
}

A RangeFrom starts at start and has no upper bound.

pub struct RangeFrom<T> {
pub start: T,
}
for i in 0.. {
if i >= 3 { break }no upper bound, so the loop sets one
fmt.Println(i)
}

A RangeTo covers up to end, excluding end.

pub struct RangeTo<T> {
pub end: T,
}
let letters = ["a", "b", "c", "d"]
let first_two = letters[..2]["a", "b"]

A RangeToInclusive covers up to end, including end.

pub struct RangeToInclusive<T> {
pub end: T,
}
let letters = ["a", "b", "c", "d"]
let first_three = letters[..=2]["a", "b", "c"]