Skip to content
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

Add Option::inspect_none & minor example improvements to other new inspect methods #94317

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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
38 changes: 36 additions & 2 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,10 +918,12 @@ impl<T> Option<T> {
/// let v = vec![1, 2, 3, 4, 5];
///
/// // prints "got: 4"
/// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
/// let a: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x));
/// assert_eq!(a, Some(&4));
///
/// // prints nothing
/// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
/// let b: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x));
/// assert_eq!(b, None);
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
Expand All @@ -938,6 +940,38 @@ impl<T> Option<T> {
self
}

/// Calls the provided closure if [`None`].
///
/// # Examples
///
/// ```
/// #![feature(result_option_inspect)]
///
/// let v = vec![1, 2, 3, 4, 5];
///
/// // prints nothing
/// let a: Option<&usize> = v.get(3).inspect_none(|| println!("index out of bound!"));
/// assert_eq!(a, Some(&4));
///
/// // prints "index out of bound!"
/// let b: Option<&usize> = v.get(5).inspect_none(|| println!("index out of bound!"));
/// assert_eq!(b, None);
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn inspect_none<F>(self, f: F) -> Self
where
F: ~const FnOnce(),
F: ~const Drop,
cyqsimon marked this conversation as resolved.
Show resolved Hide resolved
{
if let None = self {
f();
}

self
}

/// Returns the provided default result (if none),
/// or applies a function to the contained value (if any).
///
Expand Down
1 change: 1 addition & 0 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,7 @@ impl<T, E> Result<T, E> {
/// .inspect(|x| println!("original: {x}"))
/// .map(|x| x.pow(3))
/// .expect("failed to parse number");
/// assert_eq!(x, 64);
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
Expand Down