Skip to content

Add docs for question mark operator for Option #103644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,50 @@
//! }
//! ```
//!
//! # The question mark operator, `?`
//!
//! Similar to the [`Result`] type, when writing code that calls many functions that return the
//! [`Option`] type, handling `Some`/`None` can be tedious. The question mark
//! operator, [`?`], hides some of the boilerplate of propagating values
//! up the call stack.
//!
//! It replaces this:
//!
//! ```
//! # #![allow(dead_code)]
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
//! let a = stack.pop();
//! let b = stack.pop();
//!
//! match (a, b) {
//! (Some(x), Some(y)) => Some(x + y),
//! _ => None,
//! }
//! }
//!
//! ```
//!
//! With this:
//!
//! ```
//! # #![allow(dead_code)]
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
//! Some(stack.pop()? + stack.pop()?)
//! }
//! ```
//!
//! *It's much nicer!*
//!
//! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the
//! result is [`None`], in which case [`None`] is returned early from the enclosing function.
//!
//! [`?`] can be used in functions that return [`Option`] because of the
//! early return of [`None`] that it provides.
//!
//! [`?`]: crate::ops::Try
//! [`Some`]: Some
//! [`None`]: None
//!
//! # Representation
//!
//! Rust guarantees to optimize the following types `T` such that
Expand Down
7 changes: 3 additions & 4 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,10 @@
//!
//! *It's much nicer!*
//!
//! Ending the expression with [`?`] will result in the unwrapped
//! success ([`Ok`]) value, unless the result is [`Err`], in which case
//! [`Err`] is returned early from the enclosing function.
//! Ending the expression with [`?`] will result in the [`Ok`]'s unwrapped value, unless the result
//! is [`Err`], in which case [`Err`] is returned early from the enclosing function.
//!
//! [`?`] can only be used in functions that return [`Result`] because of the
//! [`?`] can be used in functions that return [`Result`] because of the
//! early return of [`Err`] that it provides.
//!
//! [`expect`]: Result::expect
Expand Down