Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
25 changes: 25 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,31 @@ impl<T> Option<T> {
}
}

/// Calls the provided closure with a reference to the contained value (if [`Some`]).
///
/// # Examples
///
/// ```
/// #![feature(result_option_inspect)]
///
/// let v = vec![1, 2, 3, 4, 5];
///
/// // prints "got: 4"
/// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x));
///
/// // prints nothing
/// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x));
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self {
if let Some(ref x) = self {
f(x);
}

self
}

/// Returns the provided default result (if none),
/// or applies a function to the contained value (if any).
///
Expand Down
47 changes: 47 additions & 0 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,53 @@ impl<T, E> Result<T, E> {
}
}

/// Calls the provided closure with a reference to the contained value (if [`Ok`]).
///
/// # Examples
///
/// ```
/// #![feature(result_option_inspect)]
///
/// let x: u8 = "4"
/// .parse::<u8>()
/// .inspect(|x| println!("original: {}", x))
/// .map(|x| x.pow(3))
/// .expect("failed to parse number");
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self {
if let Ok(ref t) = self {
f(t);
}

self
}

/// Calls the provided closure with a reference to the contained error (if [`Err`]).
///
/// # Examples
///
/// ```
/// #![feature(result_option_inspect)]
///
/// use std::{fs, io};
///
/// fn read() -> io::Result<String> {
/// fs::read_to_string("address.txt")
/// .inspect_err(|e| eprintln!("failed to read file: {}", e))
/// }
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self {
if let Err(ref e) = self {
f(e);
}

self
}

/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
Expand Down