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
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!)
> 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.
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.
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.
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
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!)
> 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.
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.
Really useful article to learn about idiomatic Rust :)
In general I think there is a lack of intermediate Rust material that teaches you common design patterns, idiomatic Rust, and so on.
Even I (someone who's written hundreds of thousands of fairly complex Rust code) learnt about the let-else style solution from this article =).
I have been using Zig a lot lately, and I just want to share the equivalent of the let-else solution in Zig:
If you only need user for a narrow scope like you would get from match, you can also use if to unwrap the optional.> My main gripe with this error message is that it doesn’t explain why the ? operator doesn’t work with Option in that case… just that it doesn’t.
The error in question:
> the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
It literally tells you why it doesn't work, wtf do you want?
I with there was a clippy check for unwrap(), I have very very rarely needed it in practice.
I'm not very familiar with Rust. Do the built in Option and Result types not implement map and flatMap?
I use a setup like this:
https://gist.github.com/tekacs/60b10000d314f9923d6b6a5af8c35...
where... in my code, I have:
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:
... etc. (there are more Reason values in the gist)This is all made available on both Result and Option.
Something I use for situations where nesting is getting out of hand. Probably not idiomatic but, I find it practical in these cases.
How long till the Rust community starts to push do notation and monad transformers?