medium.com 5 min read Original Source

Changing One Type Changes How Rust Handles Your Errors

These two Rust types look close enough to skim past:

<button data-code="Vec<Result>
Result<Vec, E>” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Vec<Result<u32, E>>
Result<Vec<u32>, E>
Vec<Result<u32, E>>
Result<Vec<u32>, E>

Give them the same parsing iterator and they behave differently. The first keeps an outcome for every row. The second stops at the first error, and the rows after it never get parsed.

I find that worth slowing down for. Moving Result outside the vector changes how much of the input your program processes. The parsing code itself can stay exactly the same.

If you are newer to Rust, Vec is a growable sequence, and Result holds either a successful value or an error. Here, u32 is an unsigned 32-bit integer and E stands for the error type. The order of those types tells us whether we get a sequence of individual outcomes or one outcome for the batch.

This matters in something as ordinary as a file import. If row seventeen fails, a configuration loader might have enough information to stop. A person correcting an upload probably wants to know about the mistakes on rows eighteen and nineteen too. Making them upload the file three times to discover three errors is an efficient way to become unpopular.

Here is a smaller input we can follow all the way through:

let rows = ["12", "7", "oops", "19", "bad"];
let rows = ["12", "7", "oops", "19", "bad"];

Treat each string as a quantity from an imported file. Parsing it produces either Ok(number) or Err(error).

The same operation, a different result type

First, keep a result for each row:

<button data-code="let rows = ["12", "7", "oops", "19", "bad"];

let outcomes: Vec<Result> = rows
.iter()
.map(|row| row.parse::())
.collect();

assert_eq!(outcomes.len(), 5);
assert!(outcomes[2].is_err());
assert_eq!(outcomes[3], Ok(19));
assert!(outcomes[4].is_err());” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let rows = ["12", "7", "oops", "19", "bad"];

let outcomes: Vec<Result<u32, _>> = rows
    .iter()
    .map(|row| row.parse::<u32>())
    .collect();

assert_eq!(outcomes.len(), 5);
assert!(outcomes[2].is_err());
assert_eq!(outcomes[3], Ok(19));
assert!(outcomes[4].is_err());
let rows = ["12", "7", "oops", "19", "bad"];

let outcomes: Vec<Result<u32, _>> = rows
    .iter()
    .map(|row| row.parse::<u32>())
    .collect();

assert_eq!(outcomes.len(), 5);
assert!(outcomes[2].is_err());
assert_eq!(outcomes[3], Ok(19));
assert!(outcomes[4].is_err());

The closure inside map attempts one conversion. Collecting into Vec<Result<u32, _>> keeps each outcome, including errors, in input order. All five rows are examined.

The underscore lets the compiler infer the parse error type. Written in full, it is std::num::ParseIntError.

Now move Result outside the vector:

<button data-code="let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec, _> = rows
.iter()
.map(|row| row.parse::())
.collect();

assert!(quantities.is_err());” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec<u32>, _> = rows
    .iter()
    .map(|row| row.parse::<u32>())
    .collect();

assert!(quantities.is_err());
let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec<u32>, _> = rows
    .iter()
    .map(|row| row.parse::<u32>())
    .collect();

assert!(quantities.is_err());

This returns the error from "oops". The caller receives no vector of successful quantities. The later strings, "19" and "bad", are never parsed by this chain.

That is quite a lot of behaviour for moving a pair of angle brackets.

The two types describe different requirements. Vec<Result<u32, E>> gives the caller an outcome for each entry. Result<Vec<u32>, E> gives the caller the complete successful collection or the first error encountered.

Why the later rows never run

It is tempting to read the chain as “parse everything, then collect the results.” But map is lazy. Creating the iterator does not parse the rows; consuming it does. Add a print inside the closure and the stopping point becomes visible:

<button data-code="let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec, _> = rows
.iter()
.map(|row| {
println!("parsing {row}");
row.parse::()
})
.collect();

assert!(quantities.is_err());” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec<u32>, _> = rows
    .iter()
    .map(|row| {
        println!("parsing {row}");
        row.parse::<u32>()
    })
    .collect();

assert!(quantities.is_err());
let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Result<Vec<u32>, _> = rows
    .iter()
    .map(|row| {
        println!("parsing {row}");
        row.parse::<u32>()
    })
    .collect();

assert!(quantities.is_err());

The expected output is:

parsing 12
parsing 7
parsing oops
parsing 12
parsing 7
parsing oops

collect() uses a trait called FromIterator to build the requested output. The standard implementation for Result stops consuming entries when it encounters an error. The vector implementation collects the individual results as values.

There is a timing detail here that matters beyond parsing. If you already built a Vec<Result<...>>, every operation used to build that vector has already happened. Collecting those stored results into a single Result afterward cannot prevent that earlier work. The early stop applies while consuming the iterator, wherever that sits in your program.

Skipping errors is easy enough to do accidentally

Suppose the requirement is to keep only valid quantities:

<button data-code="let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Vec = rows
.iter()
.filter_map(|row| row.parse::().ok())
.collect();

assert_eq!(quantities, vec![12, 7, 19]);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Vec<u32> = rows
    .iter()
    .filter_map(|row| row.parse::<u32>().ok())
    .collect();

assert_eq!(quantities, vec![12, 7, 19]);
let rows = ["12", "7", "oops", "19", "bad"];

let quantities: Vec<u32> = rows
    .iter()
    .filter_map(|row| row.parse::<u32>().ok())
    .collect();

assert_eq!(quantities, vec![12, 7, 19]);

Calling .ok() converts a success into Some(value) and an error into None. filter_map retains the values inside Some and skips None, continuing through the input.

Both invalid rows disappear. So do their error details.

For a tool whose documented job is to extract numbers from mixed input, that behaviour fits. In a customer import, I want to know where the rejected records went. A person uploading five records might reasonably expect either five imported records or an explanation of what went wrong. Three records and a cheerful success message would need some explaining.

The compiler accepts this because discarding an error is allowed. Whether the application should discard it remains our decision.

Keeping the errors useful

When the person uploading the file needs to fix it, I want the row number and rejected value alongside the error. Here is a complete example that retains successful rows too:

<button data-code="use std::num::ParseIntError;

struct RowError {
row: usize,
input: String,
cause: ParseIntError,
}

fn main() {
let rows = ["12", "7", "oops", "19", "bad"];
let mut accepted = Vec::new();
let mut rejected = Vec::new();

for (index, input) in rows.iter().enumerate() {
let row = index + 1;

match input.parse::() {
Ok(quantity) => accepted.push((row, quantity)),
Err(cause) => rejected.push(RowError {
row,
input: (*input).to_owned(),
cause,
}),
}
}
assert_eq!(accepted, vec![(1, 12), (2, 7), (4, 19)]);
assert_eq!(rejected.len(), 2);

for error in &rejected {
println!(
"Row {} ({:?}): {}",
error.row, error.input, error.cause
);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::num::ParseIntError;

struct RowError {
    row: usize,
    input: String,
    cause: ParseIntError,
}

fn main() {
    let rows = ["12", "7", "oops", "19", "bad"];
    let mut accepted = Vec::new();
    let mut rejected = Vec::new();

    for (index, input) in rows.iter().enumerate() {
        let row = index + 1;

        match input.parse::<u32>() {
            Ok(quantity) => accepted.push((row, quantity)),
            Err(cause) => rejected.push(RowError {
                row,
                input: (*input).to_owned(),
                cause,
            }),
        }
    }
    assert_eq!(accepted, vec![(1, 12), (2, 7), (4, 19)]);
    assert_eq!(rejected.len(), 2);

    for error in &rejected {
        println!(
            "Row {} ({:?}): {}",
            error.row, error.input, error.cause
        );
    }
}
use std::num::ParseIntError;

struct RowError {
    row: usize,
    input: String,
    cause: ParseIntError,
}

fn main() {
    let rows = ["12", "7", "oops", "19", "bad"];
    let mut accepted = Vec::new();
    let mut rejected = Vec::new();

    for (index, input) in rows.iter().enumerate() {
        let row = index + 1;

        match input.parse::<u32>() {
            Ok(quantity) => accepted.push((row, quantity)),
            Err(cause) => rejected.push(RowError {
                row,
                input: (*input).to_owned(),
                cause,
            }),
        }
    }
    assert_eq!(accepted, vec![(1, 12), (2, 7), (4, 19)]);
    assert_eq!(rejected.len(), 2);

    for error in &rejected {
        println!(
            "Row {} ({:?}): {}",
            error.row, error.input, error.cause
        );
    }
}

The row numbers here are positions in the sample array, starting at one. A file parser should preserve whatever location information the upload screen actually needs, especially when headers or multiline records complicate line numbering.

All five values are examined. The caller can inspect the three accepted quantities and both failures. Nothing has been written to a database yet, so a later step can reject the whole batch or proceed with the accepted rows according to the import’s rules.

I could express this with iterator adapters and separate collections. I prefer the loop here because each branch has useful work to do, and the report will probably acquire more context as the importer grows. Saving a few lines would not help the next person adding a column name to the error.

Stopping on an error does not roll back earlier work

Parsing strings makes early failure look harmless. The distinction becomes more consequential when an operation writes something.

Imagine replacing the parse closure with a call that inserts one row into a database and returns its ID. Collect the results into Result<Vec<Id>, Error>, and an error can stop subsequent calls. Successful inserts from earlier calls may already be committed. The missing vector of IDs does not mean those records are missing from the database.

For this importer, separating validation from writing gives us a useful place to make the decision. Validate the input, build the report, and decide whether the batch is acceptable. If the requirement is atomic database changes, use a transaction with an appropriate commit and rollback path. Validation alone cannot prevent a later write from failing.

The same question applies to files, notifications, and remote requests: what has already happened by the time the error reaches the caller? A return type does not supply a way to undo those effects.

For the upload screen, I want the person fixing the file to see both rejected rows in one report. The loop gives us that, along with the accepted values, before anything is written. For a loader that cannot proceed with invalid configuration, collecting into a single Result may be exactly right.

Both choices are straightforward to express once the requirement is clear. I just want the decision about the remaining rows made before someone shortens the code and accidentally makes it for us.

For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample