Skip to content

Commit b486fd5

Browse files
committed
Add docs for question mark operator for Option
1 parent aa5b179 commit b486fd5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

library/core/src/option.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,51 @@
7272
//! }
7373
//! ```
7474
//!
75+
//! # The question mark operator, `?`
76+
//!
77+
//! Similar to the [`Result`] type, when writing code that calls many functions that return the
78+
//! [`Option`] type, handling `Some`/`None` can be tedious. The question mark
79+
//! operator, [`?`], hides some of the boilerplate of propagating values
80+
//! up the call stack.
81+
//!
82+
//! It replaces this:
83+
//!
84+
//! ```
85+
//! # #![allow(dead_code)]
86+
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
87+
//! let a = stack.pop();
88+
//! let b = stack.pop();
89+
//!
90+
//! match (a, b) {
91+
//! (Some(x), Some(y)) => Some(x + y),
92+
//! _ => None,
93+
//! }
94+
//! }
95+
//!
96+
//! ```
97+
//!
98+
//! With this:
99+
//!
100+
//! ```
101+
//! # #![allow(dead_code)]
102+
//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
103+
//! Some(stack.pop()? + stack.pop()?)
104+
//! }
105+
//! ```
106+
//!
107+
//! *It's much nicer!*
108+
//!
109+
//! Ending the expression with [`?`] will result in the unwrapped
110+
//! success ([`Some`]) value, unless the result is [`None`], in which case
111+
//! [`None`] is returned early from the enclosing function.
112+
//!
113+
//! [`?`] can only be used in functions that return [`Option`] because of the
114+
//! early return of [`None`] that it provides.
115+
//!
116+
//! [`?`]: crate::ops::Try
117+
//! [`Some`]: Some
118+
//! [`None`]: None
119+
//!
75120
//! # Representation
76121
//!
77122
//! Rust guarantees to optimize the following types `T` such that

0 commit comments

Comments
 (0)