Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include the end value in a range?

Tags:

rust

I wanted to create a vector with 'a'..'z' values (inclusive).

This doesn't compile:

let vec: Vec<char> = ('a'..'z'+1).collect();

What's the idiomatic way to have 'a'..'z'?

like image 835
bohdan_trotsenko Avatar asked Apr 29 '17 16:04

bohdan_trotsenko


People also ask

Does range include last value?

By default, The range(n) is exclusive, so it doesn't include the last number in the result. It creates the sequence of numbers from start to stop -1 . For example, range(5) will produce [0, 1, 2, 3, 4] .

How do you include the last number in range Python?

In Python, you can use the built-in range() function to generate a range of numbers from the starting point until the end point. The last number in the range() call is 6, which means the last number included in the range is actually 5. In Python, you can call the range() function with one, two, or three parameters.

How do you find an inclusive range?

There really are two kinds of ranges. One is the exclusive range, which is the highest score minus the lowest score (or h − l) and the one we just defined. The second kind of range is the inclusive range, which is the highest score minus the lowest score plus 1 (or h − l + 1).

Is range inclusive or exclusive?

The exclusive type of range is most commonly used and most frequently known by the name "Range." It is obtained by differencing the highest and the smallest value of the data set. The inclusive type of range is obtained by adding 1 to the difference of the data's maximum and minimum value.


2 Answers

Rust 1.26

As of Rust 1.26, you can use "inclusive ranges":

fn main() {
    for i in 0..=26 {
        println!("{}", i);
    }
}

Rust 1.0 through 1.25

You need to add one to your end value:

fn main() {
    for i in 0..(26 + 1) {
        println!("{}", i);
    }
}

This will not work if you need to include all the values:

  • How to iterate over all byte values (overflowing_literals in `0..256`)

However, you cannot iterate over a range of characters:

error[E0277]: the trait bound `char: std::iter::Step` is not satisfied
 --> src/main.rs:2:14
  |
2 |     for i in 'a'..='z'  {
  |              ^^^^^^^^^ the trait `std::iter::Step` is not implemented for `char`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<char>`

See Why can't a range of char be collected? for solutions.

I would just specify the set of characters you are interested in:

static ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";

for c in ALPHABET.chars() {
    println!("{}", c);
}
like image 154
Shepmaster Avatar answered Oct 27 '22 07:10

Shepmaster


Inclusive range feature stabilised and released as part of version 1.26. Below is valid syntax for inclusive range

for i in 1..=3 {
    println!("i: {}", i);
}
like image 39
tsatiz Avatar answered Oct 27 '22 05:10

tsatiz