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.

Site proudly generated by Hakyll.