rust/src/libcore/bool.rs

45 lines
1.0 KiB
Rust
Raw Normal View History

2019-09-07 12:16:18 +00:00
//! impl bool {}
#[lang = "bool"]
2019-09-07 14:49:27 +00:00
impl bool {
/// Returns `Some(t)` if the `bool` is `true`, or `None` otherwise.
///
/// # Examples
///
/// ```
/// #![feature(bool_to_option)]
///
2019-10-07 23:05:13 +00:00
/// assert_eq!(false.to_option(0), None);
/// assert_eq!(true.to_option(0), Some(0));
2019-09-07 14:49:27 +00:00
/// ```
2019-09-07 16:06:39 +00:00
#[unstable(feature = "bool_to_option", issue = "64260")]
2019-09-07 14:49:27 +00:00
#[inline]
2019-10-07 23:05:13 +00:00
pub fn to_option<T>(self, t: T) -> Option<T> {
2019-09-07 14:49:27 +00:00
if self {
Some(t)
} else {
None
}
}
/// Returns `Some(f())` if the `bool` is `true`, or `None` otherwise.
///
/// # Examples
///
/// ```
/// #![feature(bool_to_option)]
///
2019-10-07 23:05:13 +00:00
/// assert_eq!(false.to_option_with(|| 0), None);
/// assert_eq!(true.to_option_with(|| 0), Some(0));
2019-09-07 14:49:27 +00:00
/// ```
2019-09-07 16:06:39 +00:00
#[unstable(feature = "bool_to_option", issue = "64260")]
2019-09-07 14:49:27 +00:00
#[inline]
2019-10-07 23:05:13 +00:00
pub fn to_option_with<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
2019-09-07 14:49:27 +00:00
if self {
Some(f())
} else {
None
}
}
}