How to Find an Element in a Vector in Rust

Find elements in a Rust vector safely using the get() method for indices or iter().find() for values.

Use the get() method to safely search for an element by index, or iter().find() to search by value.

let v = vec![1, 2, 3, 4, 5];

// Safe access by index returns Option<&i32>
if let Some(value) = v.get(2) {
    println!("Found at index 2: {value}");
}

// Search by value returns Option<&i32>
if let Some(found) = v.iter().find(|&&x| x == 3) {
    println!("Found value: {found}");
}