Fallible iterator pipelines
Quick answer
An iterator can yield Result values rather than guaranteed successes. Decide whether to reject the whole operation on failure or explicitly keep only successful items.
Collect errors or skip deliberately
Collecting into Result<Vec<T>, E> stops at the first Err and otherwise returns a vector. filter_map(|s| s.parse().ok()) discards parse errors by converting them to None; use that only if skipping invalid entries is part of the stated policy. try_fold combines processing and early failure without collecting an intermediate vector.
fn main() { let parsed: Result<Vec<i32>, _> = ["2", "bad", "4"].into_iter().map(|s| s.parse()).collect(); println!("rejected: {}", parsed.is_err());}Expected stdout (not executed):
rejected: trueA single invalid entry rejects the collected result.
fn main() { let values: Vec<i32> = ["2", "bad", "4"].into_iter().filter_map(|s| s.parse().ok()).collect(); println!("{values:?}");}Expected stdout (not executed):
[2, 4]This example deliberately implements a skip policy.
Common mistake
Never silently discard errors in a pipeline whose contract requires complete input.
Try it yourself
Use try_fold to sum parsed u16 values into u64, rejecting any malformed input.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fallible iterator pipelines — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Importing a list of quantities must fail if even one cannot be parsed. Which pipeline fits?
Fallible iterator pipelines — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let parsed: Result<Vec<i32>, _> = ["2", "bad", "4"].into_iter().map(|s| s.parse()).collect(); println!("rejected: {}", parsed.is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Fallible iterator pipelines — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let values: Vec<i32> = ["2", "bad", "4"].into_iter().filter_map(|s| s.parse().ok()).collect(); println!("{values:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.