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)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn contains(&self, x: &T) -> bool   fn binary_search(&self, x: &T) -> Result<usize, usize>

Parameters

ParameterDescription
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

Example 1
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.

Binary search and insert
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.

Was this page helpful?