about summary refs log tree commit diff
diff options
context:
space:
mode:
authorChris AtLee <chris@atlee.ca>2022-10-27 12:52:29 -0400
committerChris AtLee <chris@atlee.ca>2022-12-13 14:45:12 -0500
commitb486fd5d8300b8648eccfdde749725b3799dfa4d (patch)
treee2db5cbf18bc2c5d48eb17f0f4dc13c7c4712763
parentaa5b179599427ef233c4e47db8dac6edae22b4f8 (diff)
downloadrust-b486fd5d8300b8648eccfdde749725b3799dfa4d.tar.gz
rust-b486fd5d8300b8648eccfdde749725b3799dfa4d.zip
Add docs for question mark operator for Option
-rw-r--r--library/core/src/option.rs45
1 files changed, 45 insertions, 0 deletions
diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index 505d964e518..699e04eff2b 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -72,6 +72,51 @@
 //! }
 //! ```
 //!
+//! # 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 unwrapped
+//! success ([`Some`]) value, unless the result is [`None`], in which case
+//! [`None`] is returned early from the enclosing function.
+//!
+//! [`?`] can only 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