unwrap!

Posted on January 24, 2016 by Tommy McGuire
Labels: rust

Speaking of macros, there’s a problem with Option::unwrap. Now, I only use unwrap in a couple of instances: when I’m slapping something together to try something out and don’t want to worry about the error cases, and when I’m absolutely, positively sure it won’t fail. The problem is when unwrap does fail, it panics with an error message somewhere in option.rs, which is slightly unhelpful. When that happens while I’m slapping something together, I now have to replace all the unwrap calls with something that’ll tell me what just failed. (When it happens otherwise, I have bigger problems.)

So, I’ve come to a conclusion. unwrap should be a macro, so it can create an error message that points to what is failing.

macro_rules! unwrap {
    ($e:expr) => {
        match $e {
            Some(v) => v,
            None => panic!(concat!(stringify!($e), ": unwrap! produced None"))
        }
    }
}

(Unfortunately, I’ll need a different macro to handle Result.)

We now return you to whatever you were doing before. Thanks for your attention.

active directory applied formal logic ashurbanipal authentication books c c++ comics conference continuations coq data structure digital humanities Dijkstra eclipse virgo electronics emacs goodreads haskell http java job Knuth ldap link linux lisp math naming nimrod notation OpenAM osgi parsing pony programming language protocols python quote R random REST ruby rust SAML scala scheme shell software development system administration theory tip toy problems unix vmware yeti
Member of The Internet Defense League
Site proudly generated by Hakyll.