Let `Result::unwrap()` delegate to `Result::expect()`

In Rust 1.4.0 Result::expect() was introduced. This made Result::unwrap() basically a special case of Result::expect().

Would it make sense to refactor the implementation of Result::unwrap() to

    pub fn unwrap(self) -> T
    where
        E: fmt::Debug,
    {
        self.expect("called `Result::unwrap()` on an `Err` value")
    }

?

1 Like

only possible concern i can think of is code size regressions, since unwrap_failed mentions intentional choices made for the sake of code size, but as long as stuff gets inlined correctly, there shouldn't be any issue.

The standard library has weird code like that to reduce code size and improve compilation speed.

Delegating unwrap to expect requires additional work of inlining the method, additional work of passing through of track_caller, and additional work of merging debug info of pre-inlined and post-inlined functions. And in the end the result is the same - calling unwrap_failed.

And unwrap_failed is a standalone function used like that on purpose, because it's non-generic, marked #[cold], and supports the internal panic_immediate_abort feature.

4 Likes

Generally the answer to this question is "it's not worth spending effort on it unless there's a concrete benefit to be had". Unless it's materially better in some way -- like there's been lots of PRs that need to change both, or it'd compile faster, or something -- if it's working fine it's probably right to just leave it alone, and not spend reviewer time looking at a change.

3 Likes