@@ -61,4 +61,71 @@ impl bool {
61
61
pub fn then < T , F : FnOnce ( ) -> T > ( self , f : F ) -> Option < T > {
62
62
if self { Some ( f ( ) ) } else { None }
63
63
}
64
+
65
+ /// Returns `Ok(())` if the `bool` is [`true`](../std/keyword.true.html),
66
+ /// or `Err(err)` otherwise.
67
+ ///
68
+ /// Arguments passed to `ok_or` are eagerly evaluated; if you are
69
+ /// passing the result of a function call, it is recommended to use
70
+ /// [`ok_or_else`], which is lazily evaluated.
71
+ ///
72
+ /// [`ok_or_else`]: bool::ok_or_else
73
+ ///
74
+ /// # Examples
75
+ ///
76
+ /// ```
77
+ /// #![feature(bool_to_result)]
78
+ ///
79
+ /// assert_eq!(false.ok_or(0), Err(0));
80
+ /// assert_eq!(true.ok_or(0), Ok(()));
81
+ /// ```
82
+ ///
83
+ /// ```
84
+ /// #![feature(bool_to_result)]
85
+ ///
86
+ /// let mut a = 0;
87
+ /// let mut function_with_side_effects = || { a += 1; };
88
+ ///
89
+ /// assert!(true.ok_or(function_with_side_effects()).is_ok());
90
+ /// assert!(false.ok_or(function_with_side_effects()).is_err());
91
+ ///
92
+ /// // `a` is incremented twice because the value passed to `ok_or` is
93
+ /// // evaluated eagerly.
94
+ /// assert_eq!(a, 2);
95
+ /// ```
96
+ #[ unstable( feature = "bool_to_result" , issue = "142748" ) ]
97
+ #[ inline]
98
+ pub fn ok_or < E > ( self , err : E ) -> Result < ( ) , E > {
99
+ if self { Ok ( ( ) ) } else { Err ( err) }
100
+ }
101
+
102
+ /// Returns `Ok(())` if the `bool` is [`true`](../std/keyword.true.html),
103
+ /// or `Err(f())` otherwise.
104
+ ///
105
+ /// # Examples
106
+ ///
107
+ /// ```
108
+ /// #![feature(bool_to_result)]
109
+ ///
110
+ /// assert_eq!(false.ok_or_else(|| 0), Err(0));
111
+ /// assert_eq!(true.ok_or_else(|| 0), Ok(()));
112
+ /// ```
113
+ ///
114
+ /// ```
115
+ /// #![feature(bool_to_result)]
116
+ ///
117
+ /// let mut a = 0;
118
+ ///
119
+ /// assert!(true.ok_or_else(|| { a += 1; }).is_ok());
120
+ /// assert!(false.ok_or_else(|| { a += 1; }).is_err());
121
+ ///
122
+ /// // `a` is incremented once because the closure is evaluated lazily by
123
+ /// // `ok_or_else`.
124
+ /// assert_eq!(a, 1);
125
+ /// ```
126
+ #[ unstable( feature = "bool_to_result" , issue = "142748" ) ]
127
+ #[ inline]
128
+ pub fn ok_or_else < E , F : FnOnce ( ) -> E > ( self , f : F ) -> Result < ( ) , E > {
129
+ if self { Ok ( ( ) ) } else { Err ( f ( ) ) }
130
+ }
64
131
}
0 commit comments