From 99f3a8428e55c7ccfa940df3245ffa980f883e13 Mon Sep 17 00:00:00 2001 From: cyqsimon <28627918+cyqsimon@users.noreply.github.com> Date: Thu, 24 Feb 2022 16:44:25 +0800 Subject: [PATCH 1/2] Added `Option::inspect_none` --- library/core/src/option.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 508837f63c3be..ba3a9a14166d9 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -938,6 +938,38 @@ impl Option { 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(self, f: F) -> Self + where + F: ~const FnOnce(), + F: ~const Drop, + { + if let None = self { + f(); + } + + self + } + /// Returns the provided default result (if none), /// or applies a function to the contained value (if any). /// From e02e3edf0f09131a9b5dfb76a994e6f5c42c5ca1 Mon Sep 17 00:00:00 2001 From: cyqsimon <28627918+cyqsimon@users.noreply.github.com> Date: Thu, 24 Feb 2022 16:56:26 +0800 Subject: [PATCH 2/2] Minor improvements to examples --- library/core/src/option.rs | 6 ++++-- library/core/src/result.rs | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index ba3a9a14166d9..4eabefa3aff0f 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -918,10 +918,12 @@ impl Option { /// 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")] diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 801e3a0b3a4cc..ab87dc0d697aa 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -855,6 +855,7 @@ impl Result { /// .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")]