A batch of stock changes is all or nothing: if one entry is bad, none of them should reach the ledger. Parsing each entry gives you an iterator of Result values, one per entry, but what you want is a single answer: either every value, or the reason the batch was rejected. Writing that loop by hand means a mutable vector, an early return and care not to leak a half-filled vector to the caller.
collect can do it for you. Result implements FromIterator so that an iterator of Result<T, E> collects into Result<Vec<T>, E>. It pulls items in order, stops at the first Err and returns it; if every item is Ok, it returns Ok with all the values. The partial vector built along the way is dropped on failure, so the caller can never see half a batch. The same works for any target collection, such as Result<BTreeMap<_, _>, E>, and for Option.
Predict and run
Will the final 9 be parsed after the invalid word?
fn parse_all(input: &[&str]) -> Result<Vec<u32>, std::num::ParseIntError> {
input.iter().map(|text| text.parse()).collect()
}
fn main() {
println!("{:?}", parse_all(&["2", "4"]));
println!("Rejected: {}", parse_all(&["2", "bad", "9"]).is_err());
}Check your prediction
Ok([2, 4])
Rejected: trueThe return type alone selects the all-or-error behavior: the same .collect() with a Vec<Result<u32, _>> annotation would keep every individual result instead. Whether 9 is parsed is not visible in this output, because a rejected batch reveals nothing about the items after the error. The next example makes it visible. Before you read it, predict how many times the closure runs for ["2", "bad", "9"].
Watch collect stop early
map takes an FnMut closure, so the closure can count its own calls. That makes the short-circuit observable, and it also exposes a trap.
fn main() {
let input = ["2", "bad", "9"];
let mut calls = 0;
let mut applied = Vec::new();
let result: Result<Vec<u32>, _> = input
.iter()
.map(|text| {
calls += 1;
let value = text.parse::<u32>()?;
applied.push(value);
Ok::<u32, std::num::ParseIntError>(value)
})
.collect();
println!("result is error: {}", result.is_err());
println!("closure calls: {calls}");
println!("applied anyway: {applied:?}");
}result is error: true
closure calls: 2
applied anyway: [2]The closure ran twice: once for 2 and once for bad. collect never asked for 9, because iterators are lazy and nothing pulls the next item after an error. The second line of output is the trap. collect discards its own partial vector, but it cannot undo what your closure did: the push into applied happened before the error, and it stays. If applied were the ledger, the "rejected" batch would have changed stock. Keep the parsing stage pure, collect, and only then apply the values. Day 4's atomic batches build on exactly that order.
The Ok::<u32, std::num::ParseIntError>(value) turbofish is there because the closure's error type is otherwise ambiguous: ? could convert the parse error into many types, and the compiler needs to know which one.
First error, or every error
Stopping at the first error is the right default when the caller will fix one problem and retry, and it does no wasted work. It is a poor experience when a user submits twenty entries and must discover the bad ones one round trip at a time. For that, run every parse and split the outcomes. partition divides an iterator by a predicate, and the standard library also implements Sum for Result, which gives a one-line all-or-error total.
fn main() {
let input = ["2", "bad", "9", "-1"];
let (good, bad): (Vec<_>, Vec<_>) = input
.iter()
.enumerate()
.map(|(index, text)| (index + 1, text.parse::<u32>()))
.partition(|(_, result)| result.is_ok());
let values: Vec<u32> = good.into_iter().map(|(_, result)| result.unwrap()).collect();
println!("parsed: {values:?}");
for (position, result) in bad {
println!("entry {position}: {}", result.unwrap_err());
}
let total: Result<u32, _> = ["2", "4", "9"].iter().map(|text| text.parse::<u32>()).sum();
println!("total: {total:?}");
let failed: Result<u32, _> = ["2", "x"].iter().map(|text| text.parse::<u32>()).sum();
println!("total with an error: {}", failed.is_err());
}parsed: [2, 9]
entry 2: invalid digit found in string
entry 4: invalid digit found in string
total: Ok(15)
total with an error: truepartition visits every entry, so the report lists both bad positions. The unwrap calls are safe because each half was filtered by is_ok, though a match would make that reasoning explicit. Choose deliberately: first-error collection when the batch is cheap to resubmit, a full report when the person fixing it is a human. Either way, the ledger must not be touched until the whole batch is known to be good.
Keep the closure pure
In a map that feeds a fallible collect, compute and return values, nothing else. If you find yourself pushing, printing or writing inside it, move that work after the collect, where you know the whole batch succeeded.
Practice
Your turn
Write parse_positive(input: &[&str]) -> Result<Vec<u32>, &'static str> that rejects both invalid numbers, with "invalid number", and zero, with "zero". Assert that ["2", "0", "4"] fails with "zero" and ["x"] fails with "invalid number". Also assert that ["0", "x"] reports "zero", because the first error wins. Print the result for ["2", "4"].
fn main() {
// Define parse_positive and check the cases.
}Hint 1: the idea
Each map step returns a Result<u32, &'static str>, and collect combines them. Two different checks can fail inside the same step.
Hint 2: a first step
Use text.parse::<u32>().map_err(|_| "invalid number")? to turn the parse error into your message, then return Err("zero") or Ok(value).
Worked solution
fn parse_positive(input: &[&str]) -> Result<Vec<u32>, &'static str> {
input.iter().map(|text| {
let value = text.parse::<u32>().map_err(|_| "invalid number")?;
if value == 0 { Err("zero") } else { Ok(value) }
}).collect()
}
fn main() {
assert_eq!(parse_positive(&["2", "0", "4"]), Err("zero"));
assert_eq!(parse_positive(&["x"]), Err("invalid number"));
assert_eq!(parse_positive(&["0", "x"]), Err("zero"));
println!("{:?}", parse_positive(&["2", "4"]));
}Ok([2, 4])The ? inside the closure returns from the closure, not from parse_positive, which is why the closure's result type must match what collect expects. The ["0", "x"] case pins down ordering: x is never examined. That is fine for a pure parser, but it is also why this function cannot list every problem. The next lesson bounds how much input reaches this parser in the first place.
Completion is saved in this browser only. It does not measure mastery.