How can I check if a value is within a range?

I would like to create a Range and then check if the variable is contained in this range. Something like this:

 fn main() { let a = 3..5; assert!(a.contains(4)); } 

Now I see only the obvious thing: Iterator::any . This is ugly because it will require operation O (1) and make it O (n):

 fn main() { let mut a = 3..5; assert!(a.any(|v: i32| v == 4)); } 
+9
source share
3 answers

Starting with Rust 1.35, the source code will compile almost 1 using Range::contains :

 fn main() { let a = 3..5; assert!(a.contains(&4)); } 

1 Pass &4 instead of 4 in contains() .

+8
source

There is nothing (currently, at least) in Range itself, but it is not difficult to do; in the end, he just takes a couple of comparisons:

 4 >= a.start && 4 < a.end 
+8
source

You can also use match :

 fn main() { let v = 132; match v { 1...100 => println!("Inside"), _ => println!("Outside") } } 
+1
source

Source: https://habr.com/ru/post/1212383/


All Articles