Is a number in a range


Hi, what would you find to be the most elegant way to check if a value is in a range?

match yearday {
    0...366 => {
    // do stuff here
    _ => panic!


if let 0...366 = yearday {
// do stuff here

I see that the if let scenario is shorter, I just feel like it’s a misuse of the binding keyword let since there is no actual destructuring taking place.


There’s always the if 0 <= yearday && yearday <= 366 { ... } option too.


There’s always the option of defining the functions or method’s you’d like to use to express yourself with.

trait Contains<T> {
    fn contains(&self, T) -> bool;

impl<T: PartialOrd> Contains<T> for Range<T> {
   fn contains(&self, elt: T) -> bool { self.start >= elt && elt < self.end }

if (0..366).contains(x) { ... }


This solution was what I would have expected in the stdlib, but since it wasn’t there I asked here for the most common work around. :smiley: :+1:

Would this be enough for an RFC?


this is awesome, and this feature has been added to nightly:

There is a bug with the implementation posted here, should read self.start <= elt


For dates the range should probably be inclusive at both ends, but for completeness you probably want four range objects for each kind of range [] (] [) (). It should probably be four range types and a single contains trait function as the inclusive/exclusiveness is a property of the range.