let-else is awesome. definitely my favorite rust syntax. The compiler checks that the else branch will “diverge” (return, panic, break, or continue), so it’s impossible to mess it up.
the article says “It’s part of the standard library,” which gets the point across that it doesn’t require any external dependencies but it may be slightly misleading to those who interpret it literally - let-else a language feature, not part of the standard library, the relevant difference being that it still works in contexts that don’t have access to the standard library.
I tend to use Option::ok_or more often because it works well in long call chains. let-else is a statement, so you can’t easily insert it in the middle of my_value().do_stuff().my_field.etc(). However, Option::ok_or has the annoying issue of being slightly less efficient than let-else if you do a function call in the “or” (e.g. if you call format! to format the error message). I believe there’s a clippy lint for this, although I could be mixing it up with the lint for Option::expect (which iirc tells you to do unwrap_or_else in some cases)
I appreciate the author for writing a post explaining the “basics” of rust. I’ll include it in any training materials I give to new rust developers where I work. Too often, there’s a gap in introductory material because the vast majority of users of a programming language are not at an introductory level. e.g. in haskell, there might literally be more explanations of GADTs on the internet than there are of typeclasses
> I believe there’s a clippy lint for this, although I could be mixing it up with the lint for Option::expect (which iirc tells you to do unwrap_or_else in some cases)
I only just learned of that let-else syntax here. I haven't kept a close eye on all the changes to the language over the years, but this is exactly what I've wanted if-let to allow.
Talking about unwrapping: I’ve been using a rather aggressive list of clippy lints to prevent myself from getting panics, which are particularly deadly in real-time applications (like video games). unwrap/expect_used already got me 90% of the way out, but looking at the number of as conversions in my codebase, I think I have around 300+ numerical conversions (which can and do fail!)
This is nice, but fairly miserable to deal with in in-module unit tests, IMO.
We get around it by using conditional compilation and putting the lints in our entrypoints (`main.rs` or `lib.rs`), which is done automatically for any new entrypoint in the codebase via a Make target and some awk magic.
As an example, the following forbids print and dbg statements in release builds (all output should go through logging), allows it with a warning in debug builds, and allows it unconditionally in tests:
Yeah that is nice too, and that should also skip all the test code. I think all the clippy warnings on tests for unwrapping and such when working locally would bug me though. And at least the eglot LSP client tends to get bogged down when there are more than a thousand or so clippy warnings/errors, I have found.
All but one of these come from the restriction[1][2] lint group.
I try to remember to look at new restriction lints with every Rust release. For example, here's what new with 1.86.0[3]; the `return_and_then` lint looks pretty nice.
n.b. no one should enable all restrictions lints— some are mutually exclusive, some are appropriate for specialised circumstances like `#[no_std]`. But I find them helpful to keep a project away from the wild parts of Rust.
It was the first time I set it up, then I went through every single instance and refactored with the appropriate choice. It wasn't as tedious as you might imagine, and again, I really don't have the option of letting my game crash.
I think the only legitimate uses are for direct indexing for tile maps etc. where I do bounds checking on two axes and know that it will map correctly. to the underlying memory (but that's `clippy::indexing_slicing`, I have 0 `clippy::unwrap_used` in my codebase now).
If you begin a new project with these lints, you'll quickly train to write idiomatic Option/Result handling code by default.
yoink (although I will probably allow expect - having to provide a specific message means I'm only going to use it in cases where there's some reasonable justification)
> I find the name ok_or unintuitive and needed to look it up many times. That’s because Ok is commonly associated with the Result type, not Option.
Hmm, I kind of disagree. The method literally returns “OK or an error”. It converts an Option into a Result and the name reflects that.
There is something of an inconsistency though, although IMHO it’s worth it. The `Result::ok()` method returns a Some if it’s Ok, and None otherwise, which is concise and intuitive but indeed different from `Option::ok_or`.
Also, sometimes just unwrap it. There is some software where it's perfectly fine to panic. If there is no sane default value and there is nothing you can do to recover from the error, just unwrap.
Also, sometimes you just write software where you know the invariant is enforced so a type is never None, you can unwrap there too.
I find it interesting how a lot of people find Rust annoying because idiomatic Rust is a very strict language. You still get a ton of the benefits of Rust when writing non-idiomatic Rust. Just use the Rc<RefCell<>> and Arc<Mutex> and feel free to unwrap everything, nobody will punish you.
Goto is bad because it results in very difficult to reason about code. Using unwrap and expect is as bad as using any other language without null safety.
goto is bad when it's used in a way that makes it difficult to reason about code, but not all uses of goto are like that. The usual C pattern of `if (err) goto cleanup_resources_and_return_err;` is a good example of the use of goto that is not difficult to reason about.
Using unwrap/expect is still much better than using a language without null safety because unwrap/expect make it immediately obvious at which point a panic can occur, and creates some friction for the dev writing the code that makes them less likely to use it literally everywhere.
Anyhow warrants more than an honorable mention, IMO. anyhow::Context is great, and basically always an improvement over unwrap() - whatever complaints you might have about anyhow::Error, it's infinitely easier to handle than a panic.
Author here; thanks! I had the same impression, which is why I started writing these short-form articles about idiomatic Rust. The blog post overview is here: https://corrode.dev/blog/
Not C. C errors are different since they are simply numbers.
And spoiler alert, every language propagates errors. Sometimes automatically via exception handling, somewhat simply by returning error values.
rust does this too.
Matter fact, even javascript might be creeping toward this model of explicit error propagation soon.
The problem is that idiomatic Go reuses err for multiple calls. So if you already have one call and check err after, it counts as used, and forgetting to check it on subsequent calls is not flagged.
As for the article, I'm also a bit confused because I'm really not sure whether people write that sort of code at the beginning "very commonly" - match and `ok_or` to handle None by turning them into proper Errors is one of the first things you learn in Rust.
As others have said, you can `and_then` chain `Options`, but often it’s better to convert each `Option` into a `Result`s before chaining, to get more fine-grained error messages as shown in the fine article. But usually it’s cleaner and more convenient (and friendlier to people used to exceptions) to use the `?` operator which is basically Rust’s `do` notation except that currently you can only early-return from the entire function with it, not escape a specific block. Which in turn requires the types to match, though Rust does at least insert an `.into()` conversion for the error value.
Update: No, I don't think so. Just tried Let Else... I like it more than the ex I posted.
That said, much like it took me a while to Grok if let syntax... this will be a struggle. See the other example in this thread where the one suggesting it reversed the syntax. That will take a bit to get right...
for cases where we believe that the Result truly should never fail (for example a transaction block that passes through the inner Result value and there is no Result value in the block) and if it does then we've drastically misunderstood things.
Then, there's an enum (at the bottom of the file) of different reasons that we believe that this should never fail, like:
// e.g. we're in a service that writes to disk... and we can't write to disk
some_operation.invariant(Reason::ExternalIssue)
// we're not broken, the system wasn't set up correctly, e.g. a missing env var
some_operation.invariant(Reason::DevOps)
// this lock was poisoned... there's nothing useful that we can do _here_
some_operation.invariant(Reason::Lock)
// something in this function already checked this
some_operation.invariant(Reason::ControlFlow)
// u64 overflow of something that we increment once a second... which millennium are we in?
some_operation.invariant(Reason::SuperRare)
... etc. (there are more Reason values in the gist)
This is all made available on both Result and Option.
the article says “It’s part of the standard library,” which gets the point across that it doesn’t require any external dependencies but it may be slightly misleading to those who interpret it literally - let-else a language feature, not part of the standard library, the relevant difference being that it still works in contexts that don’t have access to the standard library.
I tend to use Option::ok_or more often because it works well in long call chains. let-else is a statement, so you can’t easily insert it in the middle of my_value().do_stuff().my_field.etc(). However, Option::ok_or has the annoying issue of being slightly less efficient than let-else if you do a function call in the “or” (e.g. if you call format! to format the error message). I believe there’s a clippy lint for this, although I could be mixing it up with the lint for Option::expect (which iirc tells you to do unwrap_or_else in some cases)
I appreciate the author for writing a post explaining the “basics” of rust. I’ll include it in any training materials I give to new rust developers where I work. Too often, there’s a gap in introductory material because the vast majority of users of a programming language are not at an introductory level. e.g. in haskell, there might literally be more explanations of GADTs on the internet than there are of typeclasses