Rust 1.99 (2024 edition) reference · Vec and HashMap
Rust slice contains, iter().position and binary_search Method
Search slices: membership, the index of a match, the first matching item, or a binary search in sorted data.
Rust 1.99 (2024 edition)
Syntax
fn contains(&self, x: &T) -> bool fn binary_search(&self, x: &T) -> Result<usize, usize>
Parameters
| Parameter | Description |
|---|---|
contains |
Linear membership test. |
iter().position(|x| ...) |
Index of the first match. |
iter().find |
The first matching item. |
binary_search |
Ok(index) or Err(insertion point) in sorted slices. |
Examples
fn main() {
let roles = ["viewer", "editor"];
println!("{}", roles.contains(&"editor"));
let temps = [12, 18, 25, 31];
println!("{:?} {:?}", temps.iter().position(|&t| t > 20), temps.iter().find(|&&t| t > 40));
}
Output
true Some(2) None
Run this on your computer — see “Get Started” for setup.
fn main() {
let mut sorted = vec![10, 20, 30, 40];
match sorted.binary_search(&25) {
Ok(i) => println!("found at {i}"),
Err(i) => { sorted.insert(i, 25); println!("inserted at {i}: {sorted:?}"); }
}
}
Output
inserted at 2: [10, 20, 25, 30, 40]
Run this on your computer — see “Get Started” for setup.
Related
Vec: push, pop, retain, dedup and sort· Grow and shrink vectors, remove items by condition, deduplicate, and sort, including by key or float values.- Rust Collections: Vec, HashMap and More · tutorial