diff --git a/library/core/src/option.rs b/library/core/src/option.rs index de1628f83ade8..c014d3d0fe41b 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")] @@ -938,6 +940,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). /// diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 9a243cbc3a2a0..37cf302ffdfa6 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -867,6 +867,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")]