snippetrustMajor
How can I test if a value lies within a Range?
Viewed 0 times
howliescanvaluerangetestwithin
Problem
I'd like to be able to create a
Right now, the only obvious thing I see is to use
Range and then test if a variable is contained in that range. Something that looks like this: fn main() {
let a = 3..5;
assert!(a.contains(4));
}Right now, the only obvious thing I see is to use
Iterator::any. This is ugly because it would take an O(1) operation and make it O(n):fn main() {
let mut a = 3..5;
assert!(a.any(|v: i32| v == 4));
}Solution
As of Rust 1.35, the original code will almost1 compile as-is using
1 Passing
Range::contains:fn main() {
let a = 3..5;
assert!(a.contains(&4));
}1 Passing
&4 instead of 4 to contains().Code Snippets
fn main() {
let a = 3..5;
assert!(a.contains(&4));
}Context
Stack Overflow Q#28265036, score: 79
Revisions (0)
No revisions yet.