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}");
}
Finding an element in a vector in Rust lets you locate items inside this list. You can ask for a specific position safely without crashing your program, or you can ask the computer to scan the list for a specific number. It's like checking a specific slot in a locker or scanning a row of lockers to find the one with your name on it.