|
233 | 233 | //! [`or_else`]: Option::or_else
|
234 | 234 | //! [`xor`]: Option::xor
|
235 | 235 | //!
|
| 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 | +//! |
236 | 266 | //! ## Iterating over `Option`
|
237 | 267 | //!
|
238 | 268 | //! An [`Option`] can be iterated over. This can be helpful if you need an
|
|
0 commit comments