Remix.run Logo
chrismorgan a day ago

One practical benefit of Rust’s approach that hasn’t been emphasised enough yet is the consequences of Option<T> and Result<T, E> being just values, same as anything else.

It means you can use things like result.map_err(|e| …) to transform an error from one type to another. (Though if there’s a suitable From conversion, and you’re going to return it, you can just write ?.)

It means you can use option.ok_or(error) or option.ok_or_else(|| error) to convert a Some(T) into an Ok(T) and a None into an Err(E).

It means you can .collect() an iterator of Result<T, E> into a Vec<Result<T, E>>, or (one of the more spectacular examples) a Result<Vec<T>, E> which is either Ok(items) or Err(first_error).

It’s rather like I found expression-orientation, when I came to Rust from Python: at first I thought it a gimmick that didn’t actually change much, just let you omit the `return` keyword or so. But now, I’m always disappointed when I work in Python or JavaScript because statement-orientation is so limiting, and so much worse.¹ Similarly, from the outside you might not see the differences between exceptions and Rust-style Result-and-? handling, but I assure you, if you lean into it, it’s hard to go back.

—⁂—

¹ I still kinda like Python, but it really painted itself into a corner, and I’ve become convinced that it chose the wrong corner in various important ways, ways that made total sense at the time, but our understanding of programming and software engineering has improved and no new general-purpose language should make such choices any more. It’s local-maximum sort of stuff.

quotemstr a day ago | parent [-]

Exceptions are values in C++, Java, and Python too. They're just values you throw. You can program these values.

As usual, I find that opposition to exceptions is rooted in a misunderstanding of what exceptions really are

chrismorgan a day ago | parent [-]

Exceptions are values, but normal-value-or-exception (which is what Result<T, E> is) isn’t a value. Review my remarks about map_err, ok_or, &c. with the understanding that Result is handling both branches of the control flow, and you can work with both together, and you might be able to see it a bit more. Try looking at real code bases using these things, with things like heavily method-chained APIs (popular in JS, but exceptions ruin the entire thing, so such APIs in JS tend to just drop errors!). And try to imagine how the collect() forms I described could work, in an exceptions world: it can’t, elegantly; not in the slightest.

Perhaps this also might be clearer: the fuss is not about the errors themselves being values, but about the entire error handling system being just values.