about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTaylor Yu <tlyu@mit.edu>2021-06-14 19:30:05 -0500
committerTaylor Yu <tlyu@mit.edu>2021-06-14 21:42:34 -0500
commit1b58d93bb20fcf8529bfe994d0c85344db5da3b8 (patch)
treeea3274d3639a05bbe2529350ac99151777836171
parent834f4b770ea58ea39ed18bd50a880e9d61bdc69f (diff)
downloadrust-1b58d93bb20fcf8529bfe994d0c85344db5da3b8.tar.gz
rust-1b58d93bb20fcf8529bfe994d0c85344db5da3b8.zip
add boolean operator example
-rw-r--r--library/core/src/option.rs30
1 files changed, 30 insertions, 0 deletions
diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index 28ea504ec0a..e79b55193c6 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -233,6 +233,36 @@
 //! [`or_else`]: Option::or_else
 //! [`xor`]: Option::xor
 //!
+//! This is an example of using methods like [`and_then`] and [`or`] in a
+//! pipeline of method calls. Early stages of the pipeline pass failure
+//! values ([`None`]) through unchanged, and continue processing on
+//! success values ([`Some`]). Toward the end, [`or`] substitutes an error
+//! message if it receives [`None`].
+//!
+//! ```
+//! # use std::collections::BTreeMap;
+//! let mut bt = BTreeMap::new();
+//! bt.insert(20u8, "foo");
+//! bt.insert(42u8, "bar");
+//! let res = vec![0u8, 1, 11, 200, 22]
+//!     .into_iter()
+//!     .map(|x| {
+//!         // `checked_sub()` returns `None` on error
+//!         x.checked_sub(1)
+//!             // same with `checked_mul()`
+//!             .and_then(|x| x.checked_mul(2))
+//!             // `BTreeMap::get` returns `None` on error
+//!             .and_then(|x| bt.get(&x))
+//!             // Substitute an error message if we have `None` so far
+//!             .or(Some(&"error!"))
+//!             .copied()
+//!             // Won't panic because we unconditionally used `Some` above
+//!             .unwrap()
+//!     })
+//!     .collect::<Vec<_>>();
+//! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
+//! ```
+//!
 //! ## Iterating over `Option`
 //!
 //! An [`Option`] can be iterated over. This can be helpful if you need an