Rollup merge of #96033 - yaahc:expect-elaboration, r=scottmcm
Add section on common message styles for Result::expect Based on a question from https://github.com/rust-lang/project-error-handling/issues/50#issuecomment-1092339937 ~~One thing I haven't decided on yet, should I duplicate this section on `Option::expect`, link to this section, or move it somewhere else and link to that location from both docs?~~: I ended up moving the section to `std::error` and referencing it from both `Result::expect` and `Option::expect`'s docs. I think this section, when combined with the similar update I made on [`std::panic!`](https://doc.rust-lang.org/nightly/std/macro.panic.html#when-to-use-panic-vs-result) implies that we should possibly more aggressively encourage and support the "expect as precondition" style described in this section. The consensus among the libs team seems to be that panic should be used for bugs, not expected potential failure modes. The "expect as error message" style seems to align better with the panic for unrecoverable errors style where they're seen as normal errors where the only difference is a desire to kill the current execution unit (aka erlang style error handling). I'm wondering if we should be providing a panic hook similar to `human-panic` or more strongly recommending the "expect as precondition" style of expect message.
This commit is contained in:
commit
82beeabf54
3 changed files with 177 additions and 1 deletions
|
@ -708,6 +708,26 @@ impl<T> Option<T> {
|
|||
/// let x: Option<&str> = None;
|
||||
/// x.expect("fruits are healthy"); // panics with `fruits are healthy`
|
||||
/// ```
|
||||
///
|
||||
/// # Recommended Message Style
|
||||
///
|
||||
/// We recommend that `expect` messages are used to describe the reason you
|
||||
/// _expect_ the `Option` should be `Some`.
|
||||
///
|
||||
/// ```should_panic
|
||||
/// # let slice: &[u8] = &[];
|
||||
/// let item = slice.get(0)
|
||||
/// .expect("slice should not be empty");
|
||||
/// ```
|
||||
///
|
||||
/// **Hint**: If you're having trouble remembering how to phrase expect
|
||||
/// error messages remember to focus on the word "should" as in "env
|
||||
/// variable should be set by blah" or "the given binary should be available
|
||||
/// and executable by the current user".
|
||||
///
|
||||
/// For more detail on expect message styles and the reasoning behind our
|
||||
/// recommendation please refer to the section on ["Common Message
|
||||
/// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue