Skip to content

Commit ef9185d

Browse files
authored
Rollup merge of #111702 - cgwalters:option-map-or-else-with-result, r=Mark-Simulacrum
Option::map_or_else: Show an example of integrating with Result Moving this from rust-lang/libs-team#59 where an API addition was rejected. But I think it's valuable to add this example to the documentation at least.
2 parents ba98957 + 440912b commit ef9185d

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

library/core/src/option.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -1138,7 +1138,7 @@ impl<T> Option<T> {
11381138
/// Computes a default function result (if none), or
11391139
/// applies a different function to the contained value (if any).
11401140
///
1141-
/// # Examples
1141+
/// # Basic examples
11421142
///
11431143
/// ```
11441144
/// let k = 21;
@@ -1149,6 +1149,25 @@ impl<T> Option<T> {
11491149
/// let x: Option<&str> = None;
11501150
/// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
11511151
/// ```
1152+
///
1153+
/// # Handling a Result-based fallback
1154+
///
1155+
/// A somewhat common occurrence when dealing with optional values
1156+
/// in combination with [`Result<T, E>`] is the case where one wants to invoke
1157+
/// a fallible fallback if the option is not present. This example
1158+
/// parses a command line argument (if present), or the contents of a file to
1159+
/// an integer. However, unlike accessing the command line argument, reading
1160+
/// the file is fallible, so it must be wrapped with `Ok`.
1161+
///
1162+
/// ```no_run
1163+
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1164+
/// let v: u64 = std::env::args()
1165+
/// .nth(1)
1166+
/// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
1167+
/// .parse()?;
1168+
/// # Ok(())
1169+
/// # }
1170+
/// ```
11521171
#[inline]
11531172
#[stable(feature = "rust1", since = "1.0.0")]
11541173
pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U

0 commit comments

Comments
 (0)