For Option types, I frequently use the ok_or
combinator to return errors like this:
let my_vec = [1,2,3];
let head = my_vec.first().cloned().ok_or(Error::MyError)?;
I am looking for a similar combinator or method to handle boolean values not Option types. For example:
let my_vec = [1,2,3];
let head = my_vec.is_empty().false_or(Error::MyError)?;
I often write matches to handle this, but it seems quite verbose:
let vec_is_ok = match my_vec.is_empty() {
true => Err(...),
false => Ok(())
}
vec_is_ok?;
Is there are more concise way to write this similar to the ok_or
combinator that i can use on boolean values?
There is a method bool::then
(added in Rust 1.50.0), returning an Option<T>
which you can convert into a Result<T, E>
.
Your example would look like this:
use std::ops::Not;
my_vec.is_empty().not().then(|| ()).ok_or(MyError)
I often write matches to handle this, but it seems quite verbose:
let vec_is_ok = match my_vec.is_empty() { true => Err(...), false => Ok(()) } vec_is_ok?;
if
is an expression and works with booleans:
let vec_is_ok = if my_vec.is_empty() { Err(...) } else { Ok(()) };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With