Skip to content

Commit a8e9708

Browse files
committed
More practical examples for Option::and_then
1 parent 5d6ee0d commit a8e9708

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

library/core/src/option.rs

+15-6
Original file line numberDiff line numberDiff line change
@@ -1207,13 +1207,22 @@ impl<T> Option<T> {
12071207
/// # Examples
12081208
///
12091209
/// ```
1210-
/// fn sq(x: u32) -> Option<u32> { Some(x * x) }
1211-
/// fn nope(_: u32) -> Option<u32> { None }
1210+
/// fn squared_string(x: u32) -> Option<String> { Some((x * x).to_string()) }
12121211
///
1213-
/// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
1214-
/// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
1215-
/// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
1216-
/// assert_eq!(None.and_then(sq).and_then(sq), None);
1212+
/// assert_eq!(Some(2).and_then(squared_string), Some(4.to_string()));
1213+
/// assert_eq!(None.and_then(squared_string), None);
1214+
/// ```
1215+
///
1216+
/// Often used to chain fallible operations that may return [`None`].
1217+
///
1218+
/// ```
1219+
/// let arr_2d = [["A1", "A2"], ["B1", "B2"]];
1220+
///
1221+
/// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1222+
/// assert_eq!(item_0_1, Some(&"A2"));
1223+
///
1224+
/// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1225+
/// assert_eq!(item_2_0, None);
12171226
/// ```
12181227
#[inline]
12191228
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)