How do I convert a RangeInclusive to a Range?

Viewed 434

So obviously I could do something like:

impl From<RangeInclusive<u32>> for Range<u32>{
    fn from(r: RangeInclusive<u32>) -> Self {
        (*r.start()..(r.end()+1))
    }
}

However I was wondering if there was already a standard function for this?(I was unable to find anything in docs/ after a quick Google). If not how would one go about implementing this for every num type, and would such an implementation be welcome to rust, or is there a reason why this is not already implemented?

1 Answers

Not every RangeInclusive can be converted to a Range, which is a major reason for RangeInclusive to exist. For instance, 0u32..=u32::MAX cannot be converted to Range<u32> because u32::MAX + 1 is out of range for u32.

It's conceivable that Range<u32> could implement TryFrom<RangeInclusive<u32>>, but such conversion should rarely be necessary. Instead of converting between different kinds of ranges, you should usually write generic APIs using RangeBounds.

Related