Skip to content

Option::map_or_else: Show an example of integrating with Result #111702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down