3 ms·
I agree unwrap is tragically overused in example code, and any non-logic error should use a Result instead — even early in a project. This isn’t a huge overhead
by codeflo 4y ago
I agree unwrap is tragically overused in example code, and any non-logic error should use a Result instead — even early in a project. This isn’t a huge overhead. Even in “prototypey” code, it’s not hard to make everything return an anyhow::Result and upgrade to more fine-grained error types later. The main function can return a Result as well (which will be unwrapped by the runtime), making this style almost as concise as the unwrap version.
I also agree that panic and crash is usually the correct response to a logic error.
However, I think library functions like Regex::new shouldn’t decide for me what I do or don’t consider a logic error — how should the library know where that string comes from? They also shouldn’t be effectively required to offer two overloads for every function just to enable both decisions: there’s already a very clean way to put that decisions into the hands of the library user, Result.unwrap() vs. Result?.
Now, about unwrap vs. expect: Since the author and I agree that panics should be reserved for logic errors, the expect() argument is effectively only a debugging aid. Should that be required? I’m torn. Often, which one I personally use reflects my confidence in getting the invariant correct and never hitting the panic in production. That can be risky. A particular team in a particular context might therefore adopt a convention to always use expect instead of unwrap, that’s fine. But I don’t think it’s unreasonable that the language offers a choice here, and in similar places, like the no-parameter variant of panic!().