Temporary unwrap calls vs. permanent ones

When I’m working on something I usually concentrate on the correct path first, so I would liberally add .unwrap() or _ => panic!() all over the place. Once I’m satisfied with the implementation, I go back and add tests (and implementations) for error handling. Sometimes, however, it’s hard to tell the difference between an .unwrap() that’s essentially a placeholder for error handling and one that’s just a runtime check for some program invariant that should always hold. (That’s not a problem with catch-alls, because I can use unreachable!().)
Is there some smart way to differentiate between the two cases for the purpose of grepping for all the placeholders?

Personally, I always use expect when I know the panic path is going to remain in place.

1 Like

There are usually ways to avoid “legitimate” unwrap, e.g.

if a.is_some() {
  a.unwrap()
}
// is
if let Some(a) = a {
}

In more complex cases you may need to get creative with Option/Result helper methods like .map(), .and_then(), but I found it’s rare where unwrap is unavoidable.

4 Likes