Collect Into Result Short Circuits On Error
Collect a mapped iterator into Result<Vec<i32>, _>: one bad element short-circuits the whole collect with the first error and leaves no partial vector.
Code
use std::num::ParseIntError;
fn main() {
let raw = ["12", "34", "56"];
// collect can fold an iterator into a Result<Vec<_>, _>:
// Ok only when everything succeeds; the first Err short-circuits immediately
let parsed: Result<Vec<i32>, ParseIntError> =
raw.iter().map(|s| s.parse::<i32>()).collect();
println!("all valid: {:?}", parsed);
let broken = ["12", "x9", "56"];
let attempt: Result<Vec<i32>, ParseIntError> =
broken.iter().map(|s| s.parse::<i32>()).collect();
// Short-circuit: no partially successful data lingers in the Vec
match attempt {
Ok(values) => println!("values {values:?}"),
Err(e) => println!("stopped at: {e}"),
}
}How it works
Collect Into Result Short Circuits On Error comes down to the function main.
Fallible operations return Result, forcing the caller to handle both arms explicitly. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Points of care
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The demo output is labeled (all valid:, values, stopped at:), so every printed line maps back to its originating operation.
Key statements
broken.iter().map(|s| s.parse::<i32>()).collect();
raw.iter().map(|s| s.parse::<i32>()).collect();
match attempt {
Ok(values) => println!("values {values:?}"),
Err(e) => println!("stopped at: {e}"),
}
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Collect Into Result Short Circuits On Error print when run?
- The script runs standalone; its 3 labeled outputs include `all valid:`, `values`, `stopped at:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.