diff options
| author | Matthias Krüger <matthias.krueger@famsik.de> | 2023-06-03 20:38:11 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-06-03 20:38:11 +0200 |
| commit | 6e024ecab8e31eca146a2a80081f0606b693a802 (patch) | |
| tree | 2c463a62a05e00c144e7985102f26acba6c1c786 /library/core | |
| parent | 91f222f931796225ded16ffe7d26a6c69e9f52f6 (diff) | |
| parent | 440912b74f5ac063d8993741120a519bed3882f2 (diff) | |
| download | rust-6e024ecab8e31eca146a2a80081f0606b693a802.tar.gz rust-6e024ecab8e31eca146a2a80081f0606b693a802.zip | |
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 https://github.com/rust-lang/libs-team/issues/59 where an API addition was rejected. But I think it's valuable to add this example to the documentation at least.
Diffstat (limited to 'library/core')
| -rw-r--r-- | library/core/src/option.rs | 21 |
1 files changed, 20 insertions, 1 deletions
diff --git a/library/core/src/option.rs b/library/core/src/option.rs index ec1ef3cf43d..b93b40e3003 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1138,7 +1138,7 @@ impl<T> Option<T> { /// Computes a default function result (if none), or /// applies a different function to the contained value (if any). /// - /// # Examples + /// # Basic examples /// /// ``` /// let k = 21; @@ -1149,6 +1149,25 @@ impl<T> Option<T> { /// let x: Option<&str> = None; /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); /// ``` + /// + /// # Handling a Result-based fallback + /// + /// A somewhat common occurrence when dealing with optional values + /// in combination with [`Result<T, E>`] is the case where one wants to invoke + /// a fallible fallback if the option is not present. This example + /// parses a command line argument (if present), or the contents of a file to + /// an integer. However, unlike accessing the command line argument, reading + /// the file is fallible, so it must be wrapped with `Ok`. + /// + /// ```no_run + /// # fn main() -> Result<(), Box<dyn std::error::Error>> { + /// let v: u64 = std::env::args() + /// .nth(1) + /// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)? + /// .parse()?; + /// # Ok(()) + /// # } + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U |
