0

I want to create a range from 2 arbitrary numbers. I would like to do this:

(a..=b)

But, as a > b is a possibility, it won't work.

I tried building a helper function, but it won't work because the .rev() trait will return a Rev<RangeInclusive<_>> not a RangeInclusive<_>.

fn create_range(a: usize, b: usize) -> ops::RangeInclusive<usize> {
    if a <= b {
        (a..=b)
    } else {
        (b..=a).rev()
    }
}

How to do this more cleanly?

gberth
  • 467
  • 5
  • 13
  • It looks like your question might be answered by the answers of [Conditionally iterate over one of several possible iterators](https://stackoverflow.com/q/29760668/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Dec 07 '21 at 21:33
  • I'm looking at your link and my rust level seems to not be good enough to get it. As there's an asymmetry between the skill level required to understand the question and the answer, I would leave my question as "open". When I understand your answer, I will update the solution here. What do you think? – gberth Dec 07 '21 at 21:42
  • But this seems to be exactly what I want: A way to specify the return type depending on `a – gberth Dec 07 '21 at 21:47
  • The duplicates [applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4f131efb7fc1c40234aaf183d7276164) – Shepmaster Dec 07 '21 at 21:54
  • This is tremendously helpful. That said, I'm disappointed by the lack of good (IMO) choices. Solution 1 needs the heap; possibly a syscall. Solution 2 is a dependency (not sure about the memory implication). Solution 3 looks great (it does the work at compile-time), but having to chain a None and an iterator feels like a hack to me. – gberth Dec 07 '21 at 22:03
  • Thanks again for your help @Shepmaster. Have a great day. – gberth Dec 07 '21 at 22:04

0 Answers0