How do I idiomatically convert a bool to an Option or Result in Rust?
As of Rust 1.50 you can use bool::then
:
assert_eq!(false.then(|| val), None);
assert_eq!(true.then(|| val), Some(val));
You can convert it to a Result
by chaining Option::ok_or
:
assert_eq!(false.then(|| val).ok_or(err), Err(err));
assert_eq!(true.then(|| val).ok_or(err), Ok(val));
As of Rust 1.62, you can use bool::then_some
and pass a value directly instead of creating a closure:
assert_eq!(false.then_some(val), None);
assert_eq!(true.then_some(val), Some(val));
Alternatively, you can use Option::filter
:
assert_eq!(Some(obj).filter(|_| false), None);
assert_eq!(Some(obj).filter(|_| true).ok_or(err), Ok(obj));
bool.then_some()
does this:
let my_bool = true;
let my_option = my_bool.then_some(MyObject{});
let my_result = my_bool.then_some(MyObject{}).ok_or(MyError{});
At the time of writing, this is still part of the experimental bool_to_option
feature.
Update: As of Rust 1.62, this feature has been stabilized.