Try Find Stops At The First Failure
try_find runs a fallible predicate and returns the first matching item or the error that stopped the search, in one pass over the data.
Code
fn parse_age(raw: &str) -> Result<u8, String> {
raw.trim().parse::<u8>().map_err(|e| format!("{raw}: {e}"))
}
fn main() {
let rows = ["21", "34", "abc", "58"];
// try_find stops at the first Err instead of scanning on: the first
// failure ends the search and carries the parse error out with it
let stopped = rows.iter().try_find(|row| parse_age(row).map(|age| age >= 65));
match stopped {
Ok(Some(row)) => println!("first senior row: {row}"),
Ok(None) => println!("no senior row"),
Err(e) => println!("search stopped: {e}"),
}
// with a clean dataset the same predicate returns Ok with a match
let clean = ["30", "44"];
let adult = clean.iter().try_find(|row| parse_age(row).map(|age| age >= 18));
match adult {
Ok(Some(row)) => println!("first adult row: {row}"),
Ok(None) => println!("no adult row"),
Err(e) => println!("stopped: {e}"),
}
}How it works
The snippet is organized around the functions parse_age and main.
Fallible operations return Result, forcing the caller to handle both arms explicitly. The match expression is exhaustive — the compiler enforces that no case is missing.
What to watch for
- The toolchain by itself is enough — no dependency resolution runs.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The signature doing the main work is fn parse_age(raw: &str) -> Result<u8, String>
Watch for labeled lines in the run — first senior row:, no senior row, search stopped: — when the file runs.
main is the driver: it invokes parse_age before returning.
Statements that matter
let stopped = rows.iter().try_find(|row| parse_age(row).map(|age| age >= 65));
let adult = clean.iter().try_find(|row| parse_age(row).map(|age| age >= 18));
fn parse_age(raw: &str) -> Result<u8, String> {
raw.trim().parse::<u8>().map_err(|e| format!("{raw}: {e}"))
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- As data, not exceptions: `Result` makes the caller handle both arms.
- What does Try Find Stops At The First Failure print when run?
- Invoke the file as-is — the `first senior row:`, `no senior row`, `search stopped:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.