Rust Lang

Rust Range

The range operator allows you to iterate over a collection of items as specified by the start and ending offset. This article will discuss common range expressions and how to use them in Rust.

Rust Range Expression

The following are some range expressions supported in the Rust language:

  1. RangeExpr
  2. Range From
  3. Range To
  4. Range Full
  5. Range Inclusive
  6. Range To Inclusive

Range

This is defined as a half-open range expression. The range operator will iterate over the items specified from the start to the end offset in this expression.

The syntax is as shown:

range start…end;

Consider the example code shown below:

fn main() {

for i in 1..5 {

println!("{}", i);

}

}

The code above will iterate from the values 1 to 5, exclusive of the end offset value. The resulting value is as shown:

1

2

3

4

Range From

Another common range expression ranges from a specific starting point to the end of the iterator.

The syntax is as shown:

start…;

Range To

The range to expression is the opposite of the range from expression. In this case, the range runs from the beginning to a specified offset value.

The syntax is as shown:

..end; // range up to

Range Full

A range full allows you to range from start to end. The syntax is as shown:

...;

Range Inclusive

To range from a specified start and end, you can use the range inclusive expression, inclusive of the high value.

The syntax is as shown:

start..=end;

Range To Inclusive

To range from the start to a specific offset and include the high value, you can use the range to expression.

The syntax is as shown:

..=end;

Closing

This is a short descriptive article on various range expressions in the Rust programming language. Consider the docs for more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list