Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make function takes both Range and RangeInclusive

Tags:

range

rust

I want a function that takes Range as it's argument.

fn takes_range(range: Range<i32>) {
    // DO SOMETING WITH RANGE
}

I can use this function like,

takes_range(0..5);

but not

takes_range(0..=5);

I realized that there are two types named Range and RangeInclusive. So if I want to takes inclusive range, should make two functions.

fn takes_range(Range<i32>) {}
fn takes_range_inclusive(RangeInclusive<i32>) {}

However this is not I want. I want to takes both Range and RangeInclusive, so I can use

takes_range(0..5);
takes_range(0..=5);

Is it possible to make my function takes both of these types?

like image 250
hardboiled65 Avatar asked Mar 09 '26 07:03

hardboiled65


1 Answers

There is a RangeBounds trait that is implemented for all the Range types. So you can make your function generic with that trait as a constraint:

use std::ops::RangeBounds;

fn takes_range<R: RangeBounds<i32>>(range: R) {
    // ...
}

However, whether this actually does what you want depends on what the "do something with range" is. Rust generics only have access to what they're constrained, so this only lets you query the range's start, end, and if a value is contained in it. If you for example wanted to use it in a for loop, you'd need to constrain on IntoIterator<Item = i32> as well.

like image 92
kmdreko Avatar answered Mar 11 '26 08:03

kmdreko



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!