如何测试一个值是否在一个范围内?

编程入门 行业动态 更新时间:2024-10-11 23:25:47
本文介绍了如何测试一个值是否在一个范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够创建一个 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 使用 按原样编译="doc.rust-lang/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().

更多推荐

如何测试一个值是否在一个范围内?

本文发布于:2023-11-07 19:25:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!