如何测试一个值是否在一个范围内? [英] How can I test if a value lies within a Range?
本文介绍了如何测试一个值是否在一个范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够创建一个 Range
然后测试变量是否包含在该范围内.看起来像这样的东西:
I'd like to be able to create a 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));
}
现在,我看到的唯一明显的事情是使用 Iterator::any
.这很丑陋,因为它需要 O(1) 操作并使其成为 O(n):
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));
}
推荐答案
从 Rust 1.35 开始,原始代码将几乎1 使用 按原样编译="https://doc.rust-lang.org/std/ops/struct.Range.html#method.contains" rel="noreferrer">Range::contains
:
As of Rust 1.35, the original code will almost1 compile as-is using Range::contains
:
fn main() {
let a = 3..5;
assert!(a.contains(&4));
}
1 将 &4
而不是 4
传递给 contains()
.
1 Passing &4
instead of 4
to contains()
.
这篇关于如何测试一个值是否在一个范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文