Skip to content

Commit 9a9dafc

Browse files
committed
explained unwrap vs expect
1 parent 7b5dce9 commit 9a9dafc

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

library/std/src/error.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,18 @@
4242
//! * `Result::unwrap`
4343
//! * `Result::expect`
4444
//!
45-
//! TODO: how do I bridge these two sections?
45+
//! These functions are equivalent, they either return the inner value if the
46+
//! `Result` is `Ok` or panic if the `Result` is `Err` printing the inner error
47+
//! as the source. The only difference between them is that with `expect` you
48+
//! provide a panic error message to be printed alongside the source, whereas
49+
//! `unwrap` has a default message indicating only that you unwraped an `Err`.
4650
//!
47-
//! * unwrap is used in prototyping
48-
//! * expect is used in !prototyping (????)
51+
//! Of the two, `expect` is generally preferred since its `msg` field allows you
52+
//! to convey your intent and assumptions which makes tracking down the source
53+
//! of a panic easier. `unwrap` on the other hand can still be a good fit in
54+
//! situations where you can trivially show that a piece of code will never
55+
//! panick, such as `"127.0.0.1".parse::<std::net::IpAddr>().unwrap()` or early
56+
//! prototyping.
4957
//!
5058
//! # Common Message Styles
5159
//!
@@ -109,14 +117,10 @@
109117
//! for why it should have been set, and we let the source error display as
110118
//! a clear contradiction to our expectation.
111119
//!
112-
//! For programs where panics may be user facing, either style works best
113-
//! when paired with a custom [panic hook] like the one provided by the CLI
114-
//! working group library, [`human-panic`]. This panic hook dumps the panic
115-
//! messages to a crash report file while showing users a more friendly
116-
//! "Oops, something went wrong!" message with a suggestion to send the
117-
//! crash report file back to the developers. Panic messages should be used
118-
//! to represent bugs, and the information provided back is context intended
119-
//! for the developer, not the user.
120+
//! **Hint**: If you're having trouble remembering how to phrase
121+
//! expect-as-precondition style error messages remember to focus on the word
122+
//! "should" as in "env variable should be set by blah" or "the given binary
123+
//! should be available and executable by the current user".
120124
//!
121125
//! [panic hook]: crate::panic::set_hook
122126
//! [`set_hook`]: crate::panic::set_hook
@@ -129,7 +133,6 @@
129133
//! [`Termination`]: crate::process::Termination
130134
//! [`Try`]: crate::ops::Try
131135
//! [`downcast`]: crate::error::Error
132-
//! [`human-panic`]: https://docs.rs/human-panic
133136
134137
#![stable(feature = "rust1", since = "1.0.0")]
135138

0 commit comments

Comments
 (0)