Skip to content

Comment on Don't unwrap options: There are better ways (2024)

Comments

I use a setup like this:

https://gist.github.com/tekacs/60b10000d314f9923d6b6a5af8c35...

where... in my code, I have:

  some_block({ ... }).infallible()
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.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.