Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range where start > end

Tags:

rust

for x in line.x1..=line.x2 {
    ...
}

This doesn't work for cases where x1 > x2, so I use this workaround:

for x in (cmp::min(line.x1, line.x2))..=(cmp::max(line.x1, line.x2)) {
    ...
}

This was fine until I needed to iterate through two fields in tandem:

for (x, y) in (line.x1..=line.x2).zip((line.y1..=line.y2)) {
    ...
}

Here my previous trick cannot work.

Is there an idiomatic way to use ranges where the start value may be greater than the end value?


Solution based on Brian's answer:

fn range_inclusive(a: usize, b: usize) -> impl Iterator<Item = usize> {
    let x: Box<dyn Iterator<Item = usize>>;
    if b > a {
        x = Box::new(a..=b)
    } else {
        x = Box::new((b..=a).rev())
    }
    x
}

fn main() {
    for i in range_inclusive(3, 1).zip(range_inclusive(1, 3)) {
        println!("{:?}", i);
    }
}
like image 540
Krish Avatar asked Mar 28 '26 01:03

Krish


1 Answers

The simplest way would be to reverse the range that you need:

for i in (0..11).rev() {
    println!("{}", i);
}

will print 10 to 0 in decreasing order.

like image 149
Jeremy Meadows Avatar answered Mar 29 '26 17:03

Jeremy Meadows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!