Skip to content

Commit a5e2b69

Browse files
committed
add boolean operator example
1 parent 22201c3 commit a5e2b69

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

core/src/option.rs

+30
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,36 @@
233233
//! [`or_else`]: Option::or_else
234234
//! [`xor`]: Option::xor
235235
//!
236+
//! This is an example of using methods like [`and_then`] and [`or`] in a
237+
//! pipeline of method calls. Early stages of the pipeline pass failure
238+
//! values ([`None`]) through unchanged, and continue processing on
239+
//! success values ([`Some`]). Toward the end, [`or`] substitutes an error
240+
//! message if it receives [`None`].
241+
//!
242+
//! ```
243+
//! # use std::collections::BTreeMap;
244+
//! let mut bt = BTreeMap::new();
245+
//! bt.insert(20u8, "foo");
246+
//! bt.insert(42u8, "bar");
247+
//! let res = vec![0u8, 1, 11, 200, 22]
248+
//! .into_iter()
249+
//! .map(|x| {
250+
//! // `checked_sub()` returns `None` on error
251+
//! x.checked_sub(1)
252+
//! // same with `checked_mul()`
253+
//! .and_then(|x| x.checked_mul(2))
254+
//! // `BTreeMap::get` returns `None` on error
255+
//! .and_then(|x| bt.get(&x))
256+
//! // Substitute an error message if we have `None` so far
257+
//! .or(Some(&"error!"))
258+
//! .copied()
259+
//! // Won't panic because we unconditionally used `Some` above
260+
//! .unwrap()
261+
//! })
262+
//! .collect::<Vec<_>>();
263+
//! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
264+
//! ```
265+
//!
236266
//! ## Iterating over `Option`
237267
//!
238268
//! An [`Option`] can be iterated over. This can be helpful if you need an

0 commit comments

Comments
 (0)