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);
}
}